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)
A to-do list changing over time
One list is reshaped five times, and each print shows the state at that moment. Predicting all five lines before reading the output is a worthwhile exercise.
todo = ["email"] todo.append("code") todo.append("gym") print(todo) todo.remove("email") print(todo) last = todo.pop() print(last) print(todo) print("code" in todo)
Output
['email', 'code', 'gym'] ['code', 'gym'] gym ['code'] True
The two append calls added to the end in order, so the list reads front to back in the order items arrived. remove deleted by value rather than position, taking "email" wherever it happened to sit. The pop line shows the method's dual nature: it printed gym because pop returns the item it removed, and the list afterwards is shorter by one. Every one of these calls modified todo itself, which is why no reassignment appears anywhere.
The build pattern with a list is the same idea as building a string, except that append extends the container instead of creating a new one each pass.
squares = [] for i in range(1, 6): squares.append(i * i) print(squares)
Output
[1, 4, 9, 16, 25]
The empty list is created before the loop so that there is something to add to on the first pass. Each pass computes one square and appends it, so the results accumulate in the order they were produced. Printing after the loop shows the finished collection, and the real advantage over the string version is that these values stay as numbers, ready for sum or max rather than needing to be parsed back out of text.
Calling lst.pop() on lst = [1, 2, 3] removes and returns the last item, leaving lst as [1, 2] and handing back 3.
The empty parentheses are what select the last position, since no index was supplied. Passing one changes the target, so pop(0) would take from the front instead and return 1.
Worth separating in your mind: pop both reads and deletes. Looking at the final item without disturbing the list is a job for plain indexing, lst[-1], which returns 3 and leaves all three items in place.