The methods that reshape a list
Real collections change while a program runs: a to-do app gains tasks, a queue of jobs drains, a shopping basket fills and empties. Lists were built for exactly this, and five methods do the reshaping:
| Method | Effect |
|---|---|
lst.append(x) | add x at the end |
lst.insert(i, x) | add x at index i, shifting the rest right |
lst.remove(x) | delete the first occurrence of x |
lst.pop() | delete AND return the last item |
lst.pop(i) | delete AND return the item at index i |
All of these change the list in place. And membership works just like it did for strings in lesson 5-3: "gym" in todo is True or False.
append is the method you will call most, because it is the list half of the build pattern from lesson 5-3: adding each new result to the end is exactly what building a collection means. It replaces string concatenation as your standard way to collect results:
squares = [] for i in range(1, 6): squares.append(i * i)
Code exercise · python
Run this to-do list session. Predict all five printed lines before running.
Code exercise · python
Your turn. Build the list of squares of 1 through 5 with the build pattern: start with an empty list, append `i * i` inside a loop, print the finished list.
Quiz
What does `lst.pop()` do to `lst = [1, 2, 3]`?