Python Arena
Step 3 of 6

Removing items: pop and remove

A queue at a counter shrinks from the front: whoever stands first is served next, whatever their name. A guest list shrinks by name: Linus cancels, wherever he is on the list. Lists have a method for each of these.

pop works with places. It removes the item at the index you give, and the items after it move one place to the left. It also returns the item it removed, so you can still use it:

queue = ["Ada", "Linus", "Grace", "Guido"]
first = queue.pop(0)
print("Now serving", first)
print(queue)
last = queue.pop()
print(last, "left the queue")
print(queue)
Output
Now serving Ada
['Linus', 'Grace', 'Guido']
Guido left the queue
['Linus', 'Grace']

Without an argument, pop() removes the last item.

remove works with values, for when you know what to take out but not where it is. It looks for the value and removes it. If the value is in the list more than once, only the first one goes:

colors = ["red", "blue", "green", "blue"]
colors.remove("blue")
print(colors)
colors.remove("blue")
print(colors)
Output
['red', 'green', 'blue']
['red', 'green']

If the value isn't in the list at all, remove stops the program:

colors = ["red", "green"]
colors.remove("pink")
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    colors.remove("pink")
    ~~~~~~~~~~~~~^^^^^^^^
ValueError: list.remove(x): x not in list

Is it in the list?

The in operator, which you know from strings, works for lists too: value in my_list is True if the value is one of the items. Check with it before you remove something that might not be there. not in is its opposite:

colors = ["red", "green"]
if "pink" in colors:
    colors.remove("pink")
else:
    print("No pink to remove")
if "yellow" not in colors:
    colors.append("yellow")
print(colors)
Output
No pink to remove
['red', 'green', 'yellow']

Your task

Challenge 1 of 3

Fill in the blanks. The program takes the first person out of the queue, prints who is served, and then removes Linus, who got tired of waiting:

Serving Ada
['Grace', 'Guido']

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Write a program for editing a playlist. It reads names of songs to remove until the user types an empty line. A song that's on the list is removed, and the program prints Removed and the song; for any other song it prints that it isn't on the list. At the end it prints the playlist:

Remove: Yesterday
Removed Yesterday
Remove: Imagine
Imagine is not on the list
Remove:
['Hey Jude', 'Let It Be']