Topic 02

Changing a List

Hands-on

A list is not fixed once it is made. Items can be added, removed, replaced and reordered, which is exactly what you need when a program collects results as it goes. Most of the tools that change a list work on the list itself and give back nothing, and that detail is behind one of the classic beginner bugs, met at the end of this page.

Think of a to-do list on a whiteboard. You add items at the bottom, rub some out, and rewrite others, all on the same board. Copying the list neatly onto a second board is a different act, and Python keeps the two just as separate.

Adding

append adds one item to the end of a list. insert puts an item at a position you choose, moving everything after it along by one. Both change the list you call them on.

Adding to a list
>>> todo = ["email", "shopping"]
>>> todo.append("laundry")
>>> todo
['email', 'shopping', 'laundry']
>>> todo.insert(0, "coffee")
>>> todo
['coffee', 'email', 'shopping', 'laundry']

Removing

remove deletes the first item equal to the value you give it. pop removes an item by position, the last one if you give no position, and hands the removed item back to you, which is useful when you want to do something with it. Removing a value that is not in the list is a ValueError, and the message says the item is not in the list.

Removing from a list
>>> todo.remove("email")
>>> todo
['coffee', 'shopping', 'laundry']
>>> done = todo.pop()
>>> done
'laundry'
>>> todo
['coffee', 'shopping']
>>> todo.remove("dishes")
Traceback (most recent call last):
  File "<python-input-10>", line 1, in <module>
    todo.remove("dishes")
    ~~~~~~~~~~~^^^^^^^^^^
ValueError: list.remove(x): x not in list

Changing One Item

To replace an item, assign to its position, exactly as you would assign to a name. Afterwards the list has the same length and a new value in that place.

Replacing an item
>>> todo[1] = "groceries"
>>> todo
['coffee', 'groceries']

Sorting: in Place or a Copy

There are two ways to sort, and the difference matters. The sort method reorders the list itself and gives back None. The sorted function leaves the original alone and gives back a new, sorted list.

Two ways to sort
>>> scores = [70, 95, 58, 81]
>>> sorted(scores)
[58, 70, 81, 95]
>>> scores
[70, 95, 58, 81]
>>> scores.sort()
>>> scores
[58, 70, 81, 95]

Now the bug. Because sort gives back None, writing scores = scores.sort() sorts the list and then points the name at the None it returned. The sorted list is lost, and printing the name shows only None. The same trap applies to append and the other methods that change a list in place; pop is the exception, since it hands back the item it removed.

sort_bug.py
scores = [70, 95, 58, 81]
scores = scores.sort()
print(scores)
Output
None
Sorting in place versus making a sorted copy
scores.sort()
The same list, now in order. Returns None.
sorted(scores)
A new sorted list. The original keeps its order.
Common Confusions
  • "sort gives back the sorted list." It gives back None. The list itself is sorted; if you need a new list, use sorted.
  • "remove deletes every match." It deletes only the first item equal to the value.
  • "pop needs a position." Without one it removes and returns the last item, which is the most common use.
Why It Matters
  • Building up a list item by item, with append, is how programs collect results as they work.
  • "Changes in place, gives back nothing" is a pattern you will meet again in Python; recognising it prevents a whole class of None surprises.

Knowledge Check

What does scores.sort() give back?

  • A new sorted list, leaving scores just as it was before
  • None, because it sorts the list itself in place
  • The smallest value, now at the front of the list
  • An error, unless the list holds only numbers

After todo = ["a", "b", "c"] and x = todo.pop(), what is x?

  • "c", the last item, which pop removed
  • "a", the first item in the list
  • None, because pop changes the list in place
  • The list ["a", "b"], what remains after pop

Why does scores = scores.sort() lose the list?

  • sort deletes every item that is out of order
  • The equals sign copies the list before sorting
  • sort returns None, and the name is tied to that None
  • A list cannot be sorted twice in one program

What does todo.insert(0, "coffee") do?

  • Replaces the first item in the list with coffee
  • Adds coffee at the end, as item number zero
  • Removes coffee if it is found at the front
  • Adds coffee at the front, moving the rest along by one

You got correct