Fundamentals · Lesson 13 of 94

Lists

Watch this lesson

View full playlist ↗

Read the lesson

What you'll learn

Concept

A list is an ordered collection of values. You write it with square brackets and commas: ["red", "green", "blue"]. The values can be any type and do not have to match, though in practice a list usually holds one kind of thing: a list of names, a list of prices, a list of rows. Order matters, duplicates are allowed, and a list can be empty.

Indexing and slicing work exactly as they did for strings, because both are sequences. colors[0] is the first item, colors[-1] the last, colors[1:3] a new list of the middle two. Everything you learned about positions starting at zero and slices excluding the stop carries over unchanged.

Lists: 'red'; 0 / -3 → 'green'; 1 / -2 → 'blue'; 2 / -1
Lists · Figure 1 · Open for full size

The difference from strings is that a list is mutable. You can change an item by assigning to its index, add items to the end with append, put one at a position with insert, and take items out with remove (by value) or pop (by position). These change the list itself; nothing is copied. That is what makes a list the right container for a collection that grows or shrinks while the program runs.

Operation Example Effect
Add at the end items.append(x) list grows by one
Add at a position items.insert(0, x) x becomes the first item
Remove by value items.remove(x) first x is deleted
Remove by position items.pop() / pop(0) last / first item removed and returned
Replace items[2] = x item at index 2 is overwritten

Mutability has a consequence you must know early. Because a list is changed in place, two names pointing at the same list both see every change. Assigning b = a does not copy the list; it gives the same list a second name. To copy, ask for one explicitly with a.copy() or a full slice a[:]. The next list lesson goes deeper; for now, remember that = never copies a list.

Lists: a → 'x', 'y' → b = a → c = a.copy() → 'x', 'y'
Lists · Figure 2 · Open for full size

Code

Creating a list, indexing it, and slicing it. The slice returns a new list, which is why printing it shows brackets.

# basics.py
colors = ["red", "green", "blue", "gold"]

print(colors)
print(len(colors))
print(colors[0], colors[-1])
print(colors[1:3])
print("blue" in colors, "pink" in colors)
Output
['red', 'green', 'blue', 'gold']
4
red gold
['green', 'blue']
True False

Changing a list in place. Each line prints the same list after a different operation, so you can see exactly what moved.

# mutate.py
tasks = ["write", "test"]

tasks.append("ship")
print(tasks)
tasks.insert(0, "plan")
print(tasks)
tasks[1] = "code"
print(tasks)
tasks.remove("test")
print(tasks)
last = tasks.pop()
print(tasks, "| popped:", last)
Output
['write', 'test', 'ship']
['plan', 'write', 'test', 'ship']
['plan', 'code', 'test', 'ship']
['plan', 'code', 'ship']
['plan', 'code'] | popped: ship

Two names, one list. Changing through b shows up in a, because they are the same list; c was copied and stays unchanged.

# aliasing.py
a = ["x", "y"]
b = a
c = a.copy()

b.append("z")

print("a:", a)
print("b:", b)
print("c:", c)
print(a is b, a is c)
Output
a: ['x', 'y', 'z']
b: ['x', 'y', 'z']
c: ['x', 'y']
True False

A loop building a list is the filter pattern from the previous lesson, now with a real list. Nothing new, but this is the form you will write constantly.

# build.py
scores = [72, 95, 58, 88, 61]
passed = []

for score in scores:
    if score >= 60:
        passed.append(score)

print(passed, len(passed), "of", len(scores))
Output
[72, 95, 88, 61] 4 of 5

Try it yourself

Create serve.py with an empty list called queue. Append three names, print the list, then serve the first person with pop(0) and print who was served and who is left. Insert a "VIP" at the front, print again, then make a copy, add a name to the copy only, and print both to prove they are separate.

Common mistakes

What's next

Lists hold items in order. Next you will meet the other essential collection, the dictionary, which finds items by name instead of by position.

Course overview