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)
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)
['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")
Traceback (most recent call last):
File "main.py", line 2, in <module>
colors.remove("pink")
~~~~~~~~~~~~~^^^^^^^^
ValueError: list.remove(x): x not in listIs 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)
No pink to remove
['red', 'green', 'yellow']