runtime
33 / 250
lesson 33 Lists & Tuples · beginner

Change a list

Unlike text, a list can change in place. append adds an item, items[i] = x replaces one, and pop removes the last one. A tuple can't change.

You'll be able to
  • Add, replace and remove items, and explain that these change the list itself
  • Build a result list in a loop, starting from []
  • Avoid items = items.append(x), and explain why a tuple raises TypeError
The idea

Text never changes, and every string method builds a new text. A list is different: it can change in place. A shopping cart is a good picture of this, because the same cart gains items, has an item swapped and loses the last one.

  • cart.append(x) adds x at the end.
  • cart[i] = x replaces the item at position i.
  • cart.pop() removes the last item and gives it back to you.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · A cart that changes
cart = []
cart.append("P0607")
cart.append("P0208")
cart.append("P0659")
print(cart, len(cart))
cart[1] = "P0209"
print(cart)
removed = cart.pop()
print(removed, cart)

Changing items through their positions is how you repair data in place. Weather stations sometimes miss a day, and the gap arrives as None. A common fix is to carry the previous day's reading forward. Loop over positions, so you can both read the previous item and replace the current one.

example-2.py · Filling gaps in the readings
temps = [6.7, None, 3.3, None, None, 3.9]
for i in range(1, len(temps)):
    if temps[i] is None:
        temps[i] = temps[i - 1]
print(temps)
example-3.py · A tuple can't change
film = ("Wild Archive", 2008)
print(film[1])
film[1] = 2009

When to use it: to collect results in a loop (start from [] and append), and to update or repair a list that the rest of the program shares. Mistakes to avoid:

  • Writing cart = cart.append(x). append changes the list and returns None, so this replaces your list with None.
  • Calling pop() on an empty list, which raises IndexError. Check len first.
Review
  • Lists change in place. append adds at the end, items[i] = x replaces, and pop() removes and returns the last item.
  • These methods return None, so call them on their own line and don't store the result.
  • Build a result by starting from [] and appending in a loop. Check len before you pop.
  • Next: sorting, and why a second name for a list is not a copy.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Change a list — Lists & Tuples · Runtime