Basic

Lists and Dictionaries

Collect and organise data with lists and key-value dictionaries.

What you will see

{0: 0, 1: 1, 2: 4, 3: 9}

About 2 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

Lists and dicts store collections I can reach by position or by name. I build and index a list, grow one with a comprehension, look values up in a dict with a safe default, unpack a tuple, and build a small mapping in a single expression.

1

Lists are ordered and changeable. I start with three numbers, grow the list, then read the first and last items and the length to see how the shape shifted.

nums = [1, 2, 3] nums.append(4) nums.insert(0, 0) print(nums[0]) print(nums[-1]) print(len(nums))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0 4 5
Indices start at 0, so nums[0] is the first item. Inserting at 0 pushes everything else down the list.
2

A comprehension replaces a loop plus an append in one line. I square every number in a range, then keep only the evens, and print both lists.

squares = [x * x for x in range(5)] print(squares) evens = [x for x in range(20) if x % 2 == 0] print(evens)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
[0, 1, 4, 9, 16] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
The optional 'if' filters items; anything after it must be a boolean expression, not an assignment.
3

A dict stores pairs I look up by key. I read one, add another, ask for a missing key with a safe default, then print every pair.

person = {"name": "Ada", "age": 30} print(person["name"]) person["city"] = "London" print(person.get("phone", "n/a")) for k, v in person.items(): print(k, v)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Ada n/a name Ada age 30 city London
person["phone"] would raise KeyError if missing; .get() returns the default instead. Keys must be unique and hashable.
4

A tuple holds a fixed record. I unpack a pair of coordinates and a three-field row straight into names, printing the variables to see the split happen.

point = (3, 4) x, y = point print(x, y) row = ("Ada", 30, "CS") name, age, dept = row print(name, age, dept)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
3 4 Ada 30 CS
Unpacking needs the same number of variables as fields. The tuple cannot change afterward, which is the point of a record.
5

A comprehension builds a dict too, not just a list. I map each number to its square and print the mapping to confirm the keys and values landed where I expected.

squares = {x: x * x for x in range(4)} print(squares)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
{0: 0, 1: 1, 2: 4, 3: 9}
The colon inside the braces separates key from value. Modern Python keeps insertion order, so iteration is stable.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

Items are stored in ordered or mapped containers and retrieved by position or key.
1 Create list/dict -> empty container
↓
2 append/set -> store new entry
↓
3 Index or key lookup -> fetch value
↓
4 Comprehension -> build new container from an iterable
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

nums = [1, 2, 3] sets nothing on screen
nums.append(4) sets nothing on screen
nums.insert(0, 0) sets nothing on screen
print(nums[0]) 0
print(nums[-1]) 4
print(len(nums)) 5
Why this works
Dictionary internals

A dict stores key/value pairs in a hash table, giving average O(1) lookup. Keys are unique and hashable; values are not. Use dict comprehensions to build them:

squares = {x: x * x for x in range(4)}  # {0:0,1:1,2:4,3:9}

Insertion order is preserved in modern Python, so iteration is stable.

When you have a choice

Lists vs tuples

Lists ([]) are mutable; tuples (()) are immutable. Choose a tuple when the data is fixed, e.g. coordinates or a record of mixed types:

point = (3, 4)
x, y = point   # unpacking

Tuples are slightly faster and can be dict keys, while lists cannot.

Examples

Building and indexing lists

Lists hold ordered items

nums = [1, 2, 3]
nums.append(4)
nums.insert(0, 0)
print(nums[0])    # 0
print(nums[-1])   # 4
print(len(nums))  # 5

Lists are mutable and ordered; indices start at 0. Use append, insert, remove, pop to change them.

List comprehensions

Concise list creation

squares = [x * x for x in range(5)]   # [0,1,4,9,16]
evens = [x for x in range(20) if x % 2 == 0]

A comprehension replaces a for loop plus append. Add an if to filter; the optional ... if ... else ... to transform conditionally.

Dictionaries lookup

Key/value storage

person = {"name": "Ada", "age": 30}
print(person["name"])          # Ada
person["city"] = "London"      # add key
person.get("phone", "n/a")     # safe default
for k, v in person.items():    # iterate
    print(k, v)

get() avoids KeyError by returning a default. Keys must be hashable; values can be anything.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Functions
Previous Lesson
Functions
Next Lesson
Error Handling
Error Handling →