Sub topic 1
A quick refresher on lists and dictionaries
This chapter reviews the parts of lists and dictionaries that the rest of the tutorial builds on. It focuses on the behaviors that matter once you start nesting: indexing, mutability, key lookup, and what a variable actually holds. If you already use these types daily, skim the headings and try the exercises.
Prerequisites
This chapter assumes you can do the following:
- Write and run basic Python: variables,
print(), and simple expressions. - Create a list and read an item by index.
- Create a dictionary and look up a value by key.
- Write a
forloop and a simple function.
You do not need to know anything about nesting yet. That starts in the next chapter.
Lists in a nutshell
A list is an ordered, mutable sequence. Ordered means items keep the position you gave them. Mutable means you can change the list after you create it, without making a new one.
scores = [90, 85, 70]
print(scores[0]) # 90
print(scores[-1]) # 70, negative indexes count from the end
print(scores[1:]) # [85, 70], a slice makes a new list
print(len(scores)) # 3Indexes start at 0. A negative index counts back from the end, so -1 is the last item. A slice such as scores[1:] returns a new list that holds the selected items.
Reading an index that does not exist raises an IndexError:
scores = [90, 85, 70]
try:
print(scores[3])
except IndexError as err:
print("bad index:", err) # bad index: list index out of rangeSlices never raise this error. They quietly return a shorter list, or an empty one.
Changing a list
Lists have several methods that change them in place.
| Operation | Effect | Example |
|---|---|---|
| `append(x)` | Adds one item to the end | `scores.append(60)` |
| `insert(i, x)` | Adds an item before index `i` | `scores.insert(0, 100)` |
| `extend(seq)` | Adds every item from another sequence | `scores.extend([50, 40])` |
| `pop(i)` | Removes and returns the item at `i` (the last by default) | `scores.pop()` |
| `remove(x)` | Removes the first item equal to `x` | `scores.remove(85)` |
| `scores[i] = x` | Replaces the item at `i` | `scores[0] = 95` |
These methods return None (except pop(), which returns the removed item). A common mistake is to write scores = scores.append(60). That sets scores to None and loses your list.
scores = [90, 85]
scores.append(70)
scores[0] = 95
removed = scores.pop()
print(scores) # [95, 85]
print(removed) # 70Dictionaries in a nutshell
A dictionary maps keys to values. You look up a value by its key, not by its position. Since Python 3.7, a dictionary also remembers the order in which keys were inserted.
student = {"name": "Ana", "age": 20}
print(student["name"]) # Ana
student["age"] = 21 # replace an existing value
student["major"] = "CS" # add a new key
print(student) # {'name': 'Ana', 'age': 21, 'major': 'CS'}Assigning to a key that exists replaces its value. Assigning to a key that does not exist adds it. The same syntax does both.
Rules for keys
A key must be hashable. In practice, that means it must be an immutable value such as a string, a number, or a tuple of immutable values. A list cannot be a key, because it can change.
good = {("x", 1): "ok"} # a tuple works as a key
try:
bad = {["x", 1]: "no"}
except TypeError as err:
print(err) # unhashable type: 'list'Values have no such restriction. A value can be any object, including another list or dictionary. That freedom is what makes nesting possible.
Looking up and removing keys
Reading a missing key with square brackets raises a KeyError. The get() method returns a default instead.
student = {"name": "Ana", "age": 20}
print(student.get("major")) # None
print(student.get("major", "undeclared")) # undeclared
print("name" in student) # True
print("Ana" in student) # False, `in` checks keys only
age = student.pop("age") # removes the key and returns its value
print(age) # 20
del student["name"] # removes the key, returns nothing
print(student) # {}Note that in tests keys, not values. To test values, use "Ana" in student.values().
Looping over a dictionary
A plain for loop over a dictionary yields its keys. Two methods give you more.
prices = {"apple": 0.5, "pear": 0.75}
for key in prices:
print(key) # apple, then pear
for value in prices.values():
print(value) # 0.5, then 0.75
for key, value in prices.items():
print(key, value) # apple 0.5, then pear 0.75items() is the form you will use most. It gives you each key and its value together, so you do not need to look the value up again inside the loop.
Do not add or remove keys while looping over a dictionary. Python raises a RuntimeError if the size changes during iteration. Changing the value of an existing key is safe.
Comparing the two types
The two types answer different questions. A list answers "what is at position n?" A dictionary answers "what is stored under this name?"
| Feature | List | Dictionary |
|---|---|---|
| Literal syntax | `[1, 2, 3]` | `{"a": 1}` |
| Lookup by | Integer position | Key |
| Order | Kept | Insertion order is kept |
| Duplicates | Allowed | Keys are unique, values may repeat |
| Missing lookup | `IndexError` | `KeyError` |
| Membership with `in` | Checks items (slow on long lists) | Checks keys (fast) |
| Safe default lookup | Check `len()` first | `get()` |
Membership tests on a dictionary are fast because keys are hashed. A test on a list compares items one at a time, so it slows down as the list grows.
What a variable holds
Everything in this tutorial depends on one fact. A variable does not contain a list or a dictionary. It holds a reference to the object, which is like a label attached to it.
Assigning one variable to another copies the reference. It does not copy the object.
a = [1, 2, 3]
b = a # b is another name for the same list
b.append(4)
print(a) # [1, 2, 3, 4]
print(a is b) # True, both names point at one objectThe is operator checks whether two names refer to the same object. The == operator checks whether two objects have equal contents. Two separate lists with the same items are == but not is.
x = [1, 2]
y = [1, 2]
print(x == y) # True
print(x is y) # FalseThe same rule applies when an object is stored inside another object. A list that holds a dictionary holds a reference to that dictionary. This is the root of the shared reference problems covered later in the tutorial.
profile = {"name": "Ana"}
team = [profile, profile] # two slots, one dictionary
team[0]["name"] = "Ben"
print(team[1]["name"]) # BenChanging the dictionary through team[0] also changes what team[1] shows, because both slots refer to the same object.
Mutable and immutable values
Lists and dictionaries are mutable, so methods and assignments change the same object. Strings, numbers, and tuples are immutable. You cannot change them in place. An operation on an immutable value produces a new value.
count = 5
other = count
count += 1
print(count, other) # 6 5, the number was replaced, not edited
items = [1]
alias = items
items += [2] # for lists, += extends in place
print(alias) # [1, 2]This difference is why b = a is harmless for numbers and strings, but surprising for lists and dictionaries. When you nest a mutable object inside another, the inner object keeps this behavior.
Making a simple copy
For a flat list or dictionary, whose values are all immutable, a basic copy is enough.
original = [1, 2, 3]
copy_one = original.copy()
copy_two = list(original)
copy_three = original[:]
copy_one.append(4)
print(original) # [1, 2, 3]
print(copy_one) # [1, 2, 3, 4]
settings = {"theme": "dark"}
settings_copy = settings.copy()
settings_copy["theme"] = "light"
print(settings["theme"]) # darkThese all produce a new outer container. They are safe here because the items are numbers and strings. Once the items are themselves lists or dictionaries, the new container still points at the same inner objects. That is a shallow copy, and it is the subject of a later chapter.
Common errors to recognize
These four errors show up constantly in nested code. Learn to read them now.
| Error | Typical cause | Fix |
|---|---|---|
| `IndexError: list index out of range` | Index is at or beyond `len(list)` | Check the length or loop instead |
| `KeyError: 'name'` | Key is not in the dictionary | Use `get()` or check with `in` |
| `TypeError: unhashable type: 'list'` | A list used as a dictionary key | Use a tuple instead |
| `RuntimeError: dictionary changed size during iteration` | Keys added or removed inside a loop over that dictionary | Loop over `list(d)` or build a new dictionary |
The last fix works because list(d) makes a snapshot of the keys first.
stock = {"apple": 0, "pear": 3, "kale": 0}
for name in list(stock):
if stock[name] == 0:
del stock[name]
print(stock) # {'pear': 3}Where this leads
You now have the pieces the next chapters combine. A list holds ordered items. A dictionary holds named values. Either one can be the value inside the other, and a variable holds a reference to the object rather than the object itself. The next chapter shows the common shapes you get when you combine them.
Exercise
A learner writes names = ["Ana", "Ben"], then backup = names, then backup.append("Cy"). What does print(names) show, and why? What one change to the second line would make names stay unchanged?
Show answer
It prints ['Ana', 'Ben', 'Cy']. The line backup = names copies the reference, so both variables name the same list, and append changes that one list. Writing backup = names.copy() (or list(names)) creates a new list, so names stays ['Ana', 'Ben'].
Exercise
Given d = {"a": 1, "b": 2}, what do "a" in d, 1 in d, and 1 in d.values() return? Then write a loop that prints each key and value on one line without looking values up by key inside the loop.
Show answer
They return True, False, and True. The in operator on a dictionary checks keys only, so 1 in d is False, and d.values() is needed to test values. The loop is for key, value in d.items(): print(key, value).
Exercise
Why does {["x", 1]: "no"} raise a TypeError, and what would you write to get a working key with the same contents?
Show answer
Dictionary keys must be hashable, and a list is mutable, so it is not hashable. Use a tuple instead: {("x", 1): "ok"}.