Lessons / Python / Unit 5

Lists and dictionaries

Lists hold values in order. Dictionaries hold values under names. Most real programs use both.

Python · Unit 5 of 5 · about 4 minutes

Lists

A list goes in square brackets. Each item has an index, starting at 0. A negative index counts from the end, so -1 is the last item.

fruits = ["apple", "pear", "plum"]

print(fruits[0])
print(fruits[-1])
print(len(fruits))
apple
plum
3

Try it

What does this print?

nums = [5, 6, 7]
print(nums[-1])
-1 means the last item, which is 7.

Changing a list

.append() adds an item to the end. You can also replace an item by assigning to its index.

nums = [1, 2]
nums.append(3)
nums[0] = 10
print(nums)
[10, 2, 3]

Try it

What does this print?

nums = [1, 2]
nums.append(3)
print(len(nums))
append added one item, so the list has three now.

Looping over a list

names = ["Ana", "Ben", "Cy"]

for name in names:
    print("Hi, " + name)
Hi, Ana
Hi, Ben
Hi, Cy

Dictionaries

A dictionary stores values under keys. It uses curly braces, and each key is followed by a colon and its value. You look things up with the key in square brackets.

pet = {"name": "Rex", "age": 3}

print(pet["name"])
pet["age"] = 4
print(pet["age"])
Rex
4

If you ask for a key that isn't there, Python stops with a KeyError. .get() gives back None instead, which is safer when you're not sure.

pet = {"name": "Rex"}

print(pet.get("color"))
print(pet["color"])
None
KeyError: 'color'

Try it

What happens when this runs?

d = {"a": 1}
print(d["b"])
There is no key "b". Square brackets raise a KeyError. d.get("b") would have given None.

Looping over a dictionary

Looping over a dictionary gives you its keys. Use the key to get each value.

scores = {"Ana": 12, "Ben": 9}

for name in scores:
    print(name, scores[name])
Ana 12
Ben 9

Common mistakes

Going past the end

In a three-item list, the last index is 2. fruits[3] gives IndexError: list index out of range.

Storing the result of append

nums = nums.append(4) replaces your list with None, because append changes the list and returns nothing. Just write nums.append(4).

Missing keys

pet["colour"] when the key is "color" gives a KeyError. Check the spelling, or use .get().

Recap

  • Lists are ordered. Indexes start at 0 and -1 is the last item.
  • len() counts items. .append() adds one.
  • Dictionaries store values under keys.
  • A missing key gives a KeyError with [ ] and None with .get().