Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Python lists and dictionaries

After this lesson: I can keep many values in lists and dictionaries.

60 min lesson3 commandsEveryday Linux commands lab: the thirty commands engineers type from memory

A shop with a hundred products

A list in Python holds many values in order, and a dictionary stores values under names you choose. Together they let one variable keep a whole shop's stock.

A shop with a hundred products cannot have a hundred separate variables. It needs one list of names and one dictionary of how many of each are left.

By the end of this lesson

Note

I can keep many values in lists and dictionaries.

Key words

WordWhat it meansExample
Listmany values kept in order["Ana", "Ben"]
Indexthe position of an item, counted from 0names[0]
Slicea part of a list, taken with a colonnames[1:3]
Dictionaryvalues stored under names, called keys{"pears": 7}
Keythe name you look a value up by
Valuethe item stored under a key

The cells students fill in are left blank in this preview.

A list keeps items in order

Write a list in square brackets, with commas between the items. Each item has an index, its position. The first item is index 0, the second is index 1, and so on.

A negative index counts from the end, so -1 is the last item. len tells you how many items there are, and append adds one at the end.

Worked example: a list of four names

ExpressionGivesWhy
names[0]"Ana"index 0 is the first
names[2]"Cara"index 2 is the third
names[-1]"Dev"negative counts from the end
len(names)4four items
names[4]an errorthe last index is 3

The cells students fill in are left blank in this preview.

First, last and how many

Command
python3 -c "names = ['Ana', 'Ben', 'Cara']; print(names[0], names[-1], len(names))"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Change and loop over a list

Code: python
names = ["Ana", "Ben", "Cara", "Dev"]
print(names[0])
print(names[-1])
names.append("Eli")
print(len(names))
for name in names:
    print("Hello,", name)
# Add a line that changes names[1] to "Bea".

A common mistake

Warning

Many people think the first item of a list has index 1. Python counts from 0, so the first item is names[0]. A list of 4 items ends at index 3, and names[4] is an error.

A slice takes part of a list

Write two indexes with a colon between them. numbers[1:4] starts at index 1 and stops before index 4.

Leave out the first number to start at the beginning. Leave out the second to go to the end. A slice is a new list, and the original is unchanged.

Worked example: slices of a list of five

ExpressionGives
numbers = [10, 20, 30, 40, 50]the list
numbers[1:4][20, 30, 40]
numbers[:2][10, 20]
numbers[3:][40, 50]
numbers[-2:][40, 50]

The cells students fill in are left blank in this preview.

Three slices of five numbers

Command
python3 -c "d = [10, 20, 30, 40, 50]; print(d[1:4], d[:2], d[3:])"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A dictionary finds a value by key

A list finds an item by its position. A dictionary finds it by a name you choose. Write it in curly brackets, with a colon between each key and its value.

stock["pears"] gives the value under the key "pears". Assign to a new key to add an entry. "plums" in stock asks whether a key is there.

Look up a key

Command
python3 -c "stock = {'apples': 4, 'pears': 7}; print(stock['pears'], 'plums' in stock, len(stock))"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A dictionary can count how often words appear

Counting is the classic job for a dictionary. Start with an empty one, {}. For each word, check whether it is already a key.

If it is, add 1 to its count. If not, store 1. text.split() turns a string into a list of its words.

Count the words in a sentence

Code: python
text = "the cat and the dog and the bird"
counts = {}
for word in text.split():
    if word in counts:
        counts[word] = counts[word] + 1
    else:
        counts[word] = 1
print(counts)
print(counts["the"])
# Change the text and run again.

Going further

Make a dictionary of your own with three entries, such as three products and their prices. Print the price of one, then add a fourth product.

Write a for loop over the dictionary and print each key with its value. Say what order you expect the keys to come in before you run it.

About this lab and its source: Everyday Linux commands lab: the thirty commands engineers type from memory

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.