Removing Items from Lists
Concepts covered: List Modification
Each way of taking items out of a list differs in what you give it and what you get back. remove takes a value and returns nothing. pop and del both take an index, but only pop hands the removed item back. Pick by what you know: the value, or the position.
remove: by value
groceries = ["milk", "eggs", "bread", "eggs", "cheese"]
print("Before:", groceries)
groceries.remove("eggs")
print("After removing eggs:", groceries)Before: ['milk', 'eggs', 'bread', 'eggs', 'cheese'] After removing eggs: ['milk', 'bread', 'eggs', 'cheese']
groceries held "eggs" twice, and only the first one went. remove searches from the front, deletes the first match and stops. A second remove("eggs") would delete the other one, and a third would fail, because the value is no longer there.
cart = ["pen", "ink"]
cart.remove("pen")
print(cart)
cart.remove("pen")
print(cart)When run, the program prints ['ink']. Then it stops with a traceback ending in ValueError: list.remove(x): x not in list. The first remove succeeded, so the second found no "pen" left and the last print never ran. The error names the problem as a value problem, which separates it from the index problems below.
pop: by index, with a return
stack = ["first", "second", "third", "fourth"]
print("Before:", stack)
# Pop without argument removes last item
last = stack.pop()
print("Popped:", last)
print("After pop():", stack)
# Pop with index removes specific item
middle = stack.pop(1)
print("Popped index 1:", middle)
print("Final:", stack)Before: ['first', 'second', 'third', 'fourth'] Popped: fourth After pop(): ['first', 'second', 'third'] Popped index 1: second Final: ['first', 'third']
pop() with no argument removes the last item and returns it. pop(1) does the same for index 1. Either way the removed item comes back, so you can store it in a variable or print it, as the animation does with last and middle.
todo = ["a", "b", "c"]
while len(todo) > 0:
item = todo.pop()
print("doing", item, "left", len(todo))
print(todo)Output:
doing c left 2 doing b left 1 doing a left 0 []
The loop stops when len(todo) hits 0. Calling pop on an empty list raises IndexError: pop from empty list, which the while condition prevents here by checking the length before each pop.
On a list of numbers, remove and pop look alike, since each takes a number in parentheses. remove reads the number as a value to find, and pop reads it as a position.
a = [5, 2, 9, 2]
a.remove(2)
print(a)
b = [5, 2, 9, 2]
b.pop(2)
print(b)Output:
[5, 9, 2] [5, 2, 2]
a.remove(2) deleted the first 2 it found, which sat at index 1. b.pop(2) went to index 2 and took 9, leaving both 2s in place. The method in front of the parentheses decides what the number means.
del: by index, no return
numbers = [10, 20, 30, 40, 50]
print("Before:", numbers)
del numbers[2]
print("After del [2]:", numbers)
del numbers[0]
print("After del [0]:", numbers)Before: [10, 20, 30, 40, 50] After del [2]: [10, 20, 40, 50] After del [0]: [20, 40, 50]
del numbers[2] deletes the item at index 2. del is a statement rather than a method, so there is no dot and no parentheses after it. After the first del, 40 moves from index 3 to index 2, so a second del numbers[2] would remove 40, not 50.
| Tool | You give | You get back | Fails when |
|---|---|---|---|
| groceries.remove("eggs") | a value | nothing | the value is absent (ValueError) |
| stack.pop() | an optional index | the removed item | the list is empty or the index is out of range, too large or too negative (IndexError) |
| del numbers[2] | an index | nothing | the index is out of range, too large or too negative (IndexError) |
What does this program print?
nums = [5, 6, 7, 8]
nums.pop(0)
del nums[-1]
nums.remove(6)
print(nums)- [7, 8]
- [5, 7]
- [6]
- [7]
Choosing among remove, pop and del
Pick the tool by what you have in hand. If you know the value, such as a guest's name, use remove. pop fits when you know the position and need the item afterwards, and it also takes negative indexes. When you know the position and have no further use for the item, del is enough.
waitlist = ["Ann", "Ben", "Cal", "Dee"]
left = waitlist.pop()
print("left:", left)
waitlist.remove("Ann")
del waitlist[0]
print(waitlist)Output:
left: Dee ['Cal']
Dee left the line from the back and her name was kept for the message, so pop fits. Ann cancelled by name, so remove fits. The front slot was dropped with no record, so del fits. Positions close up after each removal: Ben moved from index 1 to index 0 before del ran, so del took Ben and left Cal.
About this lesson
This section is part of the Lists: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.