Lesson 5 of 34 · 0 of 3 exercises solved
Lists, Dicts & Sets
, dictionaries and are Python's built-in ways to hold groups of values. Between them they cover most everyday data-handling needs.
are ordered, sequences. They're Python's workhorse collection type. You can put anything in a list — including other lists.
# Lists
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple (0-indexed)
print(fruits[-1]) # cherry (negative index = from end)
print(fruits[1:3]) # ['banana', 'cherry'] (slicing)
# Mutating lists
fruits.append("date") # add to end
fruits.insert(1, "avocado") # insert at index 1
fruits.remove("banana") # remove by value
popped = fruits.pop() # remove and return last item
fruits.sort() # sort in-place
# List comprehension — the Pythonic way to build lists
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Useful list methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(numbers)) # 8
print(sum(numbers)) # 31
print(min(numbers)) # 1
print(max(numbers)) # 9
print(numbers.count(1)) # 2Dictionaries map keys to values. As of Python 3.7+, they maintain insertion order. They're used everywhere — for config, -like data, and anything that needs fast key-based lookup.
# Dictionaries
person = {
"name": "Alice",
"age": 30,
"city": "Paris",
}
print(person["name"]) # Alice
print(person.get("country", "Unknown")) # Unknown (safe default)
# Mutating dicts
person["email"] = "alice@example.com" # add or update
del person["city"] # remove key
# Iterating
for key in person:
print(key, "->", person[key])
for key, value in person.items():
print(f"{key}: {value}")
# Dict comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Sets — unordered, unique values
tags = {"python", "web", "backend", "python"}
print(tags) # {'python', 'web', 'backend'} — duplicate removed
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a & b) # intersection: {3, 4}
print(a | b) # union: {1, 2, 3, 4, 5, 6}
print(a - b) # difference: {1, 2}Common question
Can I just use a list for everything?
Each built-in container answers a different question. A list answers "what is at position n?" and keeps things in order. A dict answers "what is the value for this key?" and finds it instantly. A set answers "is this here?" and holds each value once. A answers "what is this fixed record?" and can be hashed. Picking the one that matches your question makes code faster and clearer, because the container itself tells the reader what you meant.
Some habits that follow: count with a dict (or collections.Counter), remove duplicates with a set, return multiple values as a tuple, and keep lists for ordered sequences you will over or index. If you catch yourself writing a loop to search a list, ask whether a dict would make the search disappear.
Source: Fred Brooks, The Mythical Man-Month: "Show me your flowcharts and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won't usually need your flowcharts."
Common mix-ups
Each of these sounds reasonable. Think about why it is wrong, then open the explanation.
A list can hold anything and be searched with in, so other containers aren't needed.
A is just a list of pairs, and it doesn't keep any order.
Tuples can't be changed, so they are strictly less useful than lists.
Practice
Count how many times each word appears in the text and store the result in a dictionary called counts. Treat words case-insensitively.
Word frequencies
text = "the quick brown fox jumps over the lazy dog The DOG sleeps"
counts = {}
# split the text, then count
print(counts)
Press Run to try your code, then Check answer to grade it.Write unique_sorted(items) that returns a new list containing each value once, in ascending order. A set does the de-duplication for you.
Unique and sorted
def unique_sorted(items):
...
print(unique_sorted([3, 1, 3, 2, 1, 5]))
Press Run to try your code, then Check answer to grade it.Manage an inventory dictionary: add 5 more apples, remove the pears entirely, add a new item "kiwi" with 12, then compute total_items as the sum of all quantities.
Inventory update
inventory = {"apple": 10, "pear": 4, "banana": 7}
# 1. add 5 apples
# 2. remove pears
# 3. add 12 kiwis
# 4. total_items = sum of quantities
print(inventory, total_items)
Press Run to try your code, then Check answer to grade it.Check yourself
Which statement about tuples is true?
Tip: use the ← and → keys to move between lessons.