Course outline · 0% complete

0/32 lessons0%

Course overview →

Growing and Shrinking Lists

lesson 6-2 · ~10 min · 18/32

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:

MethodEffect
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.

14916[0][1][2][3]itemfor item in squares: the loop variable visits each cell in order
A for loop over a list: the loop variable steps through the cells one index at a time, front to back.

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]`?