Module 6 · Python for Beginners
Lists and Tuples
Store many values in one variable. Create lists, read items by index and slice, add, change and remove items, sort, search and summarise, copy safely, and when to use a tuple instead.
About 30 minutes
Open in ColabEvery example as a notebook you can run, edit and save to your Google Drive.
What a list is
A list stores many values, in order, in one variable. Write the items inside square brackets, separated by commas:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
['ECO 201', 'STA 211', 'GST 201']
[67, 81, 54]A list can hold any type, even a mix, and can be empty: []. It keeps items in the order you put them in, and can contain the same value more than once.
Reading items: indexing
Like the characters in a string, list items are numbered from 0:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
ECO 201
STA 211
CSC 201
4[0]is the first item,[1]the second.[-1]is the last item,[-2]the one before.len()counts the items. The last index is alwayslen(list) - 1.
Reading several items: slicing
list[start:stop] gives a new list from start up to, but not including, stop:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
[67, 81, 54]
[72, 45, 90]
[45, 90]
[67, 54, 45]The third number in [::2] is a step: every second item. [::-1] reverses a list.
Changing a list
Unlike strings, lists can be changed after they're made.
Changing an item
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
[67, 81, 58]Adding items
| Method | Does | Example |
|---|---|---|
append(x) | adds one item to the end | courses.append("MTH 201") |
insert(i, x) | adds an item at position i | courses.insert(0, "GST 101") |
extend(list) | adds every item of another list | courses.extend(["A", "B"]) |
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
['GST 201', 'ECO 201', 'STA 211', 'CSC 201', 'MTH 201', 'ACC 201']Removing items
| Method | Removes | Example |
|---|---|---|
remove(x) | the first item equal to x | courses.remove("STA 211") |
pop() | the last item, and gives it back | last = courses.pop() |
pop(i) | the item at position i | first = courses.pop(0) |
clear() | everything | courses.clear() |
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
['GST 201', 'ECO 201']
Dropped: CSC 201Searching
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
True
False
2in answers yes or no; index() tells you where. index() raises an error if the item isn't there, so check with in first when you're not sure. count(x) tells you how many times x appears.
Summarising numbers
Python's built-in functions work on whole lists:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
5
319
45 81
63.8That last line is the average: total divided by the number of scores.
Sorting
sort() puts a list in order, changing the list itself. sorted() gives a new sorted list and leaves the original alone:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
[81, 72, 67, 54, 45]
[67, 81, 54, 72, 45]
[45, 54, 67, 72, 81]Text sorts alphabetically, with capitals before lowercase letters. reverse=True sorts from largest to smallest, or Z to A.
Copying a list safely
This catches almost everyone once:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
[67, 81, 54, 90]copy = original doesn't copy the list: it gives the same list a second name. Changing it through one name changes it for both. To make a real copy, use .copy() or a full slice:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
[67, 81, 54]
[67, 81, 54, 90]Lists inside lists
A list can contain other lists, which is a simple way to store a table:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
['Musa', 81]
Musa 81results[1] is the second row; results[1][0] is the first item in that row.
Tuples: lists that can't change
A tuple is like a list that can't be changed after it's made. Write it with round brackets:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
6.5244
2Use a tuple for values that belong together and shouldn't change, such as coordinates, or a date as (year, month, day). Trying to change one fails:
location[0] = 9.0Output
TypeError: 'tuple' object does not support item assignmentYou can unpack a tuple (or list) into separate variables:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
6.5244 3.3792List [ ] | Tuple ( ) | |
|---|---|---|
| Can change after creation | yes | no |
| Typical use | a collection that grows or changes | a fixed group of values |
| Example | the courses you're taking | a GPS location |
When it goes wrong
scores = [67, 81, 54]
print(scores[3])Output
IndexError: list index out of rangeOff by one. Three items have positions 0, 1 and 2. Use scores[-1] for the last one.
courses = ["ECO 201", "STA 211"]
courses.remove("MTH 201")Output
ValueError: list.remove(x): x not in listRemoving something that isn't there. Check first: if "MTH 201" in courses: courses.remove("MTH 201").
scores = [67, 81, 54]
scores = scores.sort()
print(scores)Output
NoneStoring the result of sort(). sort() changes the list and returns None. Either call scores.sort() on its own line, or use scores = sorted(scores).
Summary
| You want to... | Write |
|---|---|
| make a list | items = [a, b, c] |
| the first / last item | items[0] / items[-1] |
| part of a list | items[1:3] |
| how many | len(items) |
| add to the end | items.append(x) |
| remove a value | items.remove(x) |
| check if it's there | x in items |
| total, smallest, largest | sum(items), min(items), max(items) |
| a sorted copy | sorted(items) (or reverse=True) |
| a real copy | items.copy() |
| a fixed group | point = (x, y) |
Try it
Use this list in Colab:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Practice
What is my_scores[-2]?
Practice
What is sorted(my_scores, reverse=True)[0:3]? Type the list as Python shows it.
Practice
If you run my_scores.append(90) and then print(len(my_scores)), what number is printed?
Task
8 minMake a shopping list of at least four items. Add two items (one with append, one with insert), remove one you no longer need, sort the list, then print how many items there are and the list itself. Paste your code.
Your work is checked for
- A list of at least four text items
- Uses append
- Uses insert
- Removes an item (remove or pop)
- Sorts (sort or sorted)
- Prints the count with len
Earn your badge
Take the module check
Questions on this module. Pass and you earn the Python Lists badge, free.
Create a free account to earn the badge