Lists and dictionaries

Level 4 of Python School: 3 lessons, explained from scratch, with examples.

Lesson 1

Lists

Keep many values in one variable, and pick them out by position.

A list holds many values

A list is written with square brackets and commas between the items.

Each item has a position, called its index, and the first one is 0, not 1. Negative numbers count from the end: -1 is the last item.

len() tells you how many items there are.

Python
fruits = ["mango", "apple", "kiwi"]
print(fruits[0])
print(fruits[2])
print(fruits[-1])
print(len(fruits))

Changing a list

  • pets[0] = "rabbit" replaces the item at position 0
  • pets.append("fish") adds an item to the end
  • pets.remove("dog") takes an item out
  • "dog" in pets is True or False
Python
pets = ["cat", "dog"]
pets.append("fish")
pets[0] = "rabbit"
print(pets)
print("dog" in pets)

Practise “Lists” in the game

Lesson 2

Working with lists

Loop over lists, slice them, sort them and add them up.

Looping over a list

for name in names: runs the indented lines once for each item, with name holding that item.

Python
names = ["Ama", "Li", "Omar"]
for name in names:
    print(f"Hello, {name}!")

Handy tools

  • sum(marks), min(marks) and max(marks) add up a list of numbers or find the smallest or biggest
  • sorted(marks) gives a new, sorted list (marks.sort() sorts the list itself instead)
  • marks[1:3] is a slice: the items from position 1 up to, but not including, position 3
  • marks[:2] is the first two items
Python
marks = [70, 95, 82, 64]
print(sum(marks))
print(max(marks))
print(sorted(marks))
print(marks[1:3])

Bonus: a list in one line

Making a new list from an old one is so common that Python has a short way to write it, called a list comprehension.

[n * 2 for n in nums] means “n * 2, for each n in nums”. It does the same as a loop that appends to an empty list.

Python
nums = [1, 2, 3, 4]
doubled = [n * 2 for n in nums]
print(doubled)

Practise “Working with lists” in the game

Lesson 3

Dictionaries

Look things up by name instead of by position.

Keys and values

A dictionary stores pairs: a key and its value, written key: value inside curly brackets. Like a real dictionary, you look up a word (the key) to find its meaning (the value).

ages["Ama"] gets a value. ages["Mia"] = 13 adds a new pair, or changes the value if the key is already there.

Python
ages = {"Ama": 14, "Kofi": 12}
print(ages["Ama"])
ages["Mia"] = 13
ages["Kofi"] = 13
print(ages)

Missing keys, and looping

Asking for a key that isn’t there stops with a KeyError. stock.get("plums", 0) gives back 0 instead.

"pears" in stock checks the keys. for fruit, count in stock.items(): goes through every key and value.

Python
stock = {"apples": 5, "pears": 0}
print(stock.get("plums", 0))
print("pears" in stock)
for fruit, count in stock.items():
    print(f"{fruit}: {count}")

Practise “Dictionaries” in the game

Recap

What Level 4 covers, in a few lines.

  • A list keeps many values in order: fruits = ["mango", "kiwi"]. Positions start at 0, so fruits[0] is the first and fruits[-1] the last.
  • len(list) counts the items, list.append(x) adds one to the end, and x in list checks whether it’s there.
  • for item in list: goes through a list. sum(), min(), max() and sorted() work on lists of numbers, and list[1:3] takes a slice.
  • A dictionary looks things up by a key instead of a position: ages = {"Ama": 14}, then ages["Ama"].
  • A missing key stops with a KeyError; d.get(key, default) gives a default instead. for key, value in d.items(): goes through every pair.

Now try it in Python School

Write real Python and run it right there, with a check after every step and a test at the end of each level. Free.

Start learning