Python Book · Chapter 6

Lists and dictionaries

Real programs handle many values at once: every student in a class, every word in a file. Lists and dictionaries are Python's everyday tools for that.

Lists

A list is an ordered collection, written with square brackets:

langs = ["Python", "C", "Java"]
print(langs[0])    # Python  (counting starts at 0)
print(langs[-1])   # Java    (negative counts from the end)
print(len(langs))  # 3

Changing a list

langs.append("Rust")    # add to the end
langs.insert(1, "Go")   # add at position 1
langs.remove("C")       # remove by value
last = langs.pop()      # remove and return the last item
langs[0] = "Python 3"   # replace an item
print(langs)

Use in to check membership: if "Go" in langs:.

Slicing

A slice takes part of a list (or a string) with [start:stop]. As with range, the stop index is not included.

nums = [10, 20, 30, 40, 50]
nums[1:3]   # [20, 30]
nums[:2]    # [10, 20]
nums[3:]    # [40, 50]
nums[::-1]  # [50, 40, 30, 20, 10]

Looping over a list

scores = [72, 88, 95, 61]
for s in scores:
    print(s)

for i, s in enumerate(scores):
    print(f"Student {i + 1}: {s}")

print(sum(scores) / len(scores))  # average

List comprehensions

A comprehension builds a new list from an old one in a single line:

squares = [n * n for n in range(6)]
# [0, 1, 4, 9, 16, 25]

passed = [s for s in scores if s >= 70]
# [72, 88, 95]

Dictionaries

A dictionary maps keys to values, so you can look things up by name instead of position:

student = {"name": "Ada", "year": 2, "major": "CS"}
print(student["name"])        # Ada
student["year"] = 3           # update
student["gpa"] = 3.8          # add a new key
print(student.get("minor"))   # None instead of an error
print("major" in student)     # True

Looking up a key with square brackets raises a KeyError if it is missing. .get() returns None, or a default you choose: student.get("minor", "none").

Looping over a dictionary

for key, value in student.items():
    print(f"{key}: {value}")

Counting with a dictionary

Dictionaries are perfect for counting things:

text = "the cat and the hat"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
# {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}

Exercises

1. Largest and smallest

Given nums = [4, 17, 2, 9], print the largest number, the smallest number and the list sorted from high to low.

Show answer
print(max(nums))                      # 17
print(min(nums))                      # 2
print(sorted(nums, reverse=True))     # [17, 9, 4, 2]

sorted returns a new list. nums.sort() sorts the original list in place instead.

2. Phone book

Create a dictionary of three names and phone numbers. Ask the user for a name and print the number, or "Not found" if the name is missing.

Show answer
book = {
    "ada": "555-0101",
    "grace": "555-0102",
    "linus": "555-0103",
}
name = input("Name: ").lower()
print(book.get(name, "Not found"))

3. Comprehension practice

Using a list comprehension, make a list of the lengths of each word in "lists are really useful".split().

Show answer
words = "lists are really useful".split()
lengths = [len(w) for w in words]
print(lengths)  # [5, 3, 6, 6]

What next?

You now know enough Python to solve many of the daily problems. Try one today. The next six chapters go further: more about functions and dictionaries, then files, classes, errors and testing.