Lists & Tuples: Ordered Collections
Keep many values in one variable: create lists, read items by position, add, remove, sort and search, slice and copy safely, and use tuples for fixed groups of values. Then see why two names can point to one list.
Why collections?
Real programs work with many values: 30 temperatures, 200 customers, 10,000 messages. Creating a separate variable for each would be hopeless. A collection holds many values under one name. Python's most used collection is the list: an ordered sequence, like a numbered shopping list.
temps = [28.4, 31.2, 29.9, 33.1]
names = ["Sita", "Leo", "Mia"]
mixed = [3, "three", 3.0, True] # allowed, but usually a list holds one kind of thing
empty = []
print(temps)
print(len(names)) # how many items: 3
print(names[0], names[-1]) # first and last: Sita Mia
print("Leo" in names) # TrueReading and changing items
Lists use the same indexes and slices as strings: the first item is [0], the last [-1], and [1:3] is a new list of items 1 and 2. Unlike strings, lists are mutable: you can change them in place.
scores = [70, 85, 62, 90, 77]
scores[2] = 65 # replace the item at position 2
print(scores)
print(scores[1:4]) # a slice: [85, 65, 90]
print(scores[:2], scores[-2:])Adding, removing and searching
| Do this | Code | Notes |
|---|---|---|
| add to the end | xs.append(9) | the most common way to grow a list |
| add at a position | xs.insert(0, 9) | 0 = at the front |
| add several | xs.extend([7, 8]) | or xs + [7, 8] for a new list |
| remove by value | xs.remove(9) | removes the first 9; error if there is none |
| remove by position | xs.pop() / xs.pop(0) | removes and returns the item (last by default) |
| find a position | xs.index(9) | error if missing; check with in first |
| count a value | xs.count(9) | |
| empty it | xs.clear() |
queue = ["Sita", "Leo"]
queue.append("Mia") # Mia joins the end
queue.insert(0, "Ana") # Ana jumps to the front
print(queue)
served = queue.pop(0) # take the first person
print("serving", served, "| still waiting:", queue)
queue.remove("Leo") # Leo leaves
print(queue, len(queue))
if "Zoe" in queue:
print(queue.index("Zoe"))
else:
print("Zoe is not in the queue")Sorting
There are two ways, and the difference catches everyone out once:
xs.sort()sorts the list in place and returnsNone.sorted(xs)returns a new sorted list and leavesxsunchanged. It works on any collection.
Add reverse=True for largest first. To sort by something other than the value itself, give a key: a function applied to each item, such as key=len to sort words by length (you will write your own key functions in the More Functions lesson).
scores = [70, 85, 62, 90, 77]
ranked = sorted(scores, reverse=True)
print(ranked, scores) # scores is unchanged
scores.sort()
print(scores) # now sorted in place
words = ["kiwi", "fig", "banana", "apple"]
print(sorted(words)) # alphabetical
print(sorted(words, key=len)) # by length
result = scores.sort()
print(result) # None: sort() changes the list and returns nothingBuilding lists with a loop
A very common pattern: start with an empty list, loop, and append what you want to keep. This is how you filter (keep some items) and transform (change every item). Later, in Pythonic Python, you will write the same thing in one line as a list comprehension.
temps_c = [18, 25, 31, 22, 35]
hot = []
for t in temps_c:
if t > 30:
hot.append(t) # filter: keep only some
print("hot days:", hot)
temps_f = []
for t in temps_c:
temps_f.append(round(t * 9 / 5 + 32, 1)) # transform: change each
print("in Fahrenheit:", temps_f)Names point to lists: why copying matters
A variable is a name attached to an object, not a box holding its own copy. After b = a, both names point to the same list, so changing it through b also changes what you see through a. This surprises almost everyone the first time.
To get an independent copy, use a.copy(), list(a) or a[:]. (For lists that contain other lists, copy.deepcopy(a) copies the inner lists too.)
Watch the code run: two names, one list
Step through and watch which names point to which list.
Interactive: this part runs in your browser.
Tuples: fixed groups of values
A tuple is like a list that cannot be changed, written with round brackets: point = (3, 4). Use a tuple for a small group of values that belong together and should stay fixed: a coordinate, an RGB colour, a (name, score) pair. Functions often return several values as a tuple.
Unpacking gives each item its own name in one line. It works with lists too, and it is how Python swaps two variables without a temporary one.
point = (3, 4)
x, y = point # unpacking
print(x, y)
brisbane = (-27.47, 153.03) # latitude, longitude
lat, lon = brisbane
print(f"lat {lat}, lon {lon}")
a, b = 1, 2
a, b = b, a # swap
print(a, b)
pairs = [("Sita", 82), ("Leo", 91)]
for name, score in pairs: # unpacking inside a for loop
print(name, score)
single = (5,) # a one-item tuple needs the comma
print(type(single), len(point))
# point[0] = 10 would be a TypeError: tuples cannot be changedLists of lists
A list can hold other lists, which is a simple way to represent a table or a grid. Use two indexes: the first picks the row, the second the column.
grid = [
[1, 2, 3],
[4, 5, 6],
]
print(grid[1]) # the second row: [4, 5, 6]
print(grid[1][2]) # row 1, column 2: 6
for row in grid:
print(sum(row)) # total of each rowPractice: check yourself
Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.
Start from items = ["milk", "bread"]. Add "eggs" to the end, add "coffee" at the front, remove "bread", and finally set count to the number of items. The final list is ["coffee", "milk", "eggs"].
From temps = [18, 31, 25, 36, 29, 33] build two new lists with loops: hot, the temperatures above 30, and fahrenheit, every temperature converted with c * 9 / 5 + 32.
scores = [72, 95, 64, 88, 91, 70]. Set top3 to the three highest scores, highest first ([95, 91, 88]), without changing scores.
Summary
Lists are ordered and changeable: index, slice, append, insert, remove, pop and sort them. = never copies a list; use .copy(). Tuples are fixed lists, great for small groups of values and for unpacking.
Key words
- list
- an ordered, changeable collection:
[1, 2, 3] - item / element
- one value in a collection
- mutable
- can be changed in place (lists); immutable cannot (tuples, strings)
- method
- a function used with a dot:
xs.append(4) - tuple
- an ordered collection that cannot change:
(3, 4) - unpacking
- giving each item of a sequence its own name:
x, y = point - alias
- a second name for the same object
Common mistakes
xs = xs.sort()sets xs toNone. Usexs.sort()on its own, orxs = sorted(xs).- IndexError: list index out of range. A list of 5 items has positions 0–4.
b = athen changing b and being surprised a changed: copy witha.copy().xs.append(4, 5): append takes one item. Useextend([4, 5]).xs.remove(x)when x might not be there: checkif x in xsfirst.
Quiz
1. Which line safely reads a key that might be missing from dict d?
2. xs = [10, 20, 30, 40]. What is xs[1:3]?
3. xs = [10, 20, 30, 40]. What is xs[-2]?
4. a = [1, 2]; b = a; b.append(3). What is a?
5. What is the difference between xs.sort() and sorted(xs)?
6. What does xs.pop() do?
7. Why use a tuple instead of a list?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- The Python Tutorial: Data Structures ↗ lists, tuples, sets, dictionaries and comprehensions
- Think Python, 3rd edition (Allen Downey) ↗ free online textbook that teaches thinking like a programmer