8. Lists & Tuples

Lists & Tuples

So far each variable has held a single value. Often you need to hold many values together: a shopping list, exam scores, a playlist. Python's list is the workhorse for ordered collections, and the tuple is its unchangeable cousin.

Creating and reading a list

Write a list with square brackets and commas. Items can be any type, and a list keeps them in order. Access items by index, exactly like string characters, and slice them the same way:

PYTHON
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[-1])
print(fruits[0:2])
print(len(fruits))
▸ OUTPUT
apple
cherry
['apple', 'banana']
3
"apple" "banana" "cherry" index 0 index 1 index 2

Lists are mutable

Unlike strings, lists can be changed in place. You can replace an item by index and use methods to grow or shrink the list.

MethodWhat it doesExample on [1, 2]
.append(x)Add x to the end[1, 2, 3]
.insert(i, x)Insert x at index i.insert(0, 9) gives [9, 1, 2]
.pop()Remove and return last itemreturns 2, list is [1]
.remove(x)Remove first matching value.remove(1) gives [2]
.sort()Sort the list in place[2, 1].sort() gives [1, 2]
PYTHON
scores = [70, 90, 55]
scores.append(80)
scores.sort()
print(scores)
top = scores.pop()
print(top, scores)
▸ OUTPUT
[55, 70, 80, 90]
90 [55, 70, 80]

Tuples and immutability

A tuple looks like a list but uses round brackets and cannot be changed after creation. Use a tuple when the collection should stay fixed, such as a coordinate pair or a date:

PYTHON
point = (3, 4)
print(point[0])
print(point[1])
# point[0] = 9   # this would raise a TypeError
▸ OUTPUT
3
4

Because tuples cannot change, Python can handle them slightly faster and they are safe to use as fixed records. You can also unpack a tuple into several variables at once: x, y = point gives x = 3 and y = 4.

A gentle look at list comprehensions

A very common task is building a new list by transforming each item of an old one. The long way uses a loop:

PYTHON
squares = []
for n in range(1, 6):
    squares.append(n * n)
print(squares)
▸ OUTPUT
[1, 4, 9, 16, 25]

Python offers a shorter form called a list comprehension that does the same thing in one line:

PYTHON
squares = [n * n for n in range(1, 6)]
print(squares)

evens = [n for n in range(10) if n % 2 == 0]
print(evens)
▸ OUTPUT
[1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]

Read it as "collect n * n for each n in the range." You can add an if at the end to keep only some items. Comprehensions are concise and popular, but a normal loop is just as correct when it reads more clearly.

Lists and tuples let you manage collections of data with ease. Practice by making a list of your five favourite numbers, then printing their total with the built-in sum() function.