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.
- 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
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)addsxat the end.cart[i] = xreplaces the item at positioni.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.
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.
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)
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).appendchanges the list and returnsNone, so this replaces your list withNone. - Calling
pop()on an empty list, which raises IndexError. Checklenfirst.
- Lists change in place.
appendadds at the end,items[i] = xreplaces, andpop()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. Checklenbefore youpop. - Next: sorting, and why a second name for a list is not a copy.