Part 3: Python Programming
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:
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.
| Method | What it does | Example 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 item | returns 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] |
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:
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 offers a shorter form called a list comprehension that does the same thing in one line:
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.