CollectionsChapter 28 of 114
Remove Items
remove, pop, del and clear, and which one to reach for.
remove takes a value
names = ["Ada", "Grace", "Katherine"]
names.remove("Grace")
print(names)Output
['Ada', 'Katherine']
It removes the first match only, and raises ValueError when there is none:
names = ["Ada", "Grace", "Ada"]
names.remove("Ada")
print(names)
try:
names.remove("Alan")
except ValueError as problem:
print("ValueError:", problem)Output
['Grace', 'Ada'] ValueError: list.remove(x): x not in list
pop takes a position and hands the item back
names = ["Ada", "Grace", "Katherine"]
last = names.pop()
first = names.pop(0)
print(last, first)
print(names)Output
Katherine Ada ['Grace']
With no argument pop() takes the last item, which makes a list a perfectly good stack. pop() is the one removal method that returns something useful.
del removes by position
names = ["Ada", "Grace", "Katherine"]
del names[1]
print(names)Output
['Ada', 'Katherine']
del also takes a slice, which removes a whole stretch:
numbers = [0, 1, 2, 3, 4, 5]
del numbers[1:4]
print(numbers)Output
[0, 4, 5]
And del on the name itself removes the name:
numbers = [1, 2]
del numbers
print("the name is gone")Output
the name is gone
clear empties the list
names = ["Ada", "Grace"]
names.clear()
print(names, len(names))Output
[] 0
clear() keeps the same list object, so other names pointing at it see it emptied. names = [] would give you a new empty list and leave theirs alone.
a = [1, 2]
b = a
a.clear()
print(b)Output
[]
Removing several
Removing while looping goes wrong, as the previous chapter showed. Build the list you want instead:
numbers = [1, 2, 3, 4, 5, 6]
numbers = [n for n in numbers if n % 2 != 0]
print(numbers)Output
[1, 3, 5]
To empty in place while other names watch, assign to a full slice:
a = [1, 2, 3, 4]
b = a
a[:] = [n for n in a if n > 2]
print(b)Output
[3, 4]
Which to use
| You know | Use |
|---|---|
| the value | remove(value) |
| the position, and want the item | pop(index) |
| the position, and do not want it | del items[index] |
| you want it all gone | clear() |
Test yourself
2 questionsWhat does names.remove("Ada") do when Ada appears twice?
Show the answer
Removes the first one only — remove drops the first match. It raises ValueError when there is none at all.
Which removal method hands the item back to you?
Show the answer
pop() — That is what makes append and pop together a perfectly good stack.
Loop Lists
Walk a list properly, with the index when you need it and without when you do not.