D. Removing Items with remove()
๐ฏ Learning Goals
By the end of this lesson, you'll be able to:
- โ
remove()function to remove items - โ Be able to remove enemies/bullets in a game
- โ Understand the cautions when removing
Core Concepts
What is remove()?
remove() function removes a specific item from a list.
๐๏ธ Analogy: a trash can
Just like Trash canLike throwing something into a trash can! It finds the specified item and removes it.
Syntax
Using it in games
enemies = [enemy1, enemy2, enemy3]
# Remove when an enemy dies
enemies.remove(enemy1)
destroy(enemy1) # Remove from the screen too
Cautions
โ ๏ธ Caution!
In the list, an item that isn't there trying to remove it causes an error!
Example Code
from ursina import *
app = Ursina()
# Target list
targets = []
# Create 6 targets
for i in range(6):
target = Entity(
model='cube',
color=color.white,
position=(i*2 - 5, 0, 5)
)
targets.append(target)
print(f"Target count: {len(targets)}") # 6
# Remove the first target
first = targets[0]
targets.remove(first)
destroy(first)
print(f"Target count: {len(targets)}") # 5
app.run()
What Happens
1 of 6 is removed, leaving 5!
Quiz
Show Answer
Answer: B) A ValueError occurs
Trying to remove an item that isn't there causes an error! It's safer to check whether the item exists before removing it.
remove() practice:
fruits = ["์ฌ๊ณผ", "๋ฐ๋๋", "์ค๋ ์ง"] Given a list:
- "๋ฐ๋๋" to remove it:
fruits.("๋ฐ๋๋")โ["์ฌ๊ณผ", "์ค๋ ์ง"] - If you remove an item that isn't in the list: Occurs
- Before removing, "ํฌ๋" check whether it exists:
if "ํฌ๋"fruits:
๐ง Debug Clinic
Problem: ValueError: list.remove(x): x not in list
โ Wrong Code
Cause: Trying to remove an item that isn't in the listโ Correct Code
Fix: Before removing,in keyword to check!
Try Coding It Yourself
Take what you learned with the blocks and write it yourself in Python code!
Removing with remove()
Remove a specific item from the list.
Example Answer
fruits = ['Apple', 'Banana', 'Orange', 'Grape']
print(f'Before removing: {fruits}')
fruits.remove('Banana')
print(f'After removing: {fruits}')
Result: The list with '๋ฐ๋๋' removed is printed!
Removing safely
Check whether the item exists, then remove it!
๐งฉ Key Takeaways
What you learned in this lesson:
| Concept | Description |
|---|---|
| remove() | Remove an item from a list |
| Syntax | list.remove(item) |
| Caution | Error when removing a nonexistent item |
| Safety check | if item in list: |
Review Checklist
- [ ]
remove()Can you explain the role of the function? - [ ] Do you know which error occurs when you try to remove a nonexistent item?
- [ ]
inkeyword, can you check whether an item exists?