🐸

Discarding

Python Basicspython-basics-27-discarding
Reward: 130 XP
|

Discarding

The backpack is getting too heavy! Hoppy needs to throw away some rocks.

You can remove items using .pop() (by index) or .remove() (by value).

Removal Spells

backpack = ["Key", "Map", "Rock", "Compass"]

# .pop(index) removes and returns item at index
# If no index is given, it removes the LAST one.
trash = backpack.pop(2) # Removes "Rock" at index 2

# .remove(value) removes the FIRST matching item
backpack.remove("Compass")
# Now: ["Key", "Map"]

Your Mission

1
Heavy Bag

Start with bag = ["Gold", "Rock", "Map", "Rock"].

2
Pop it

Use .pop(1) to remove the item at index 1 ("Rock").

3
Remove it

Use .remove("Rock") to remove the other "Rock".

4
Check

Print the bag.

Suggested Solution
Click to expand

Be careful! .remove() will give an error if the item isn't there.

bag = ["Gold", "Rock", "Map", "Rock"]
bag.pop(1)
bag.remove("Rock")
print(bag)
Advanced Tips
Want more? Click to expand

del is another way to remove items by index or slice.

del bag[0] # Removes "Gold"
pymain.py
Loading...
Terminal
Terminal
Ready to run...