List Comprehensions
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — The Problem
Imagine you want to create a new list based on an existing one. For example, getting the level of each Codémon doubled. With a `for` loop, you'd do this:
levels = [5, 12, 8, 25]
doubled = []
for lv in levels:
doubled.append(lv * 2)
print(doubled)That works, but it's 4 lines for something simple. Python has a shorter way.
Exercise 2 — List Comprehensions
A list comprehension lets you create a list in just one line. The syntax is: `[expression for item in iterable]`
levels = [5, 12, 8, 25]
doubled = [lv * 2 for lv in levels]
print(doubled)How to read it
Try to read it the 'wrong way' to understand it better! Start with the `for` part: 'For each `lv` in the `levels`...'. Then look at the `expression`: '...apply `lv * 2`.
Same result, one line! The `expression` (`lv * 2`) is applied to each `item` (`lv`) in the `iterable` (`levels`).
Exercise 3 — More Examples
You can use any expression — call functions, use methods, do math... anything that returns a value.
team = ["Aquachu", "Pyrochu", "Florachu"]
upper_team = [name.upper() for name in team]
print(upper_team)team = ["Aquachu", "Pyrochu", "Florachu"]
lengths = [len(name) for name in team]
print(lengths)Exercise 4 — Comprehension Output
result = [x * 2 for x in [1, 2, 3]]
print(result)What is printed?
Hint : The expression `x * 2` is applied to each element in the list.
Exercise 5 — Complete the Comprehension
Complete the list comprehension to get the length of each Codémon name.
Hint : You need a function that returns the length, and a keyword to iterate over the list.
Exercise 6 — Transform Elements
Complete the comprehension to convert each level to a string.
Hint : Which function converts a number to a string?
Exercise 7 — Filtering with if
You can add a condition to only include elements that match. The syntax becomes: `[expression for item in iterable if condition]`
levels = [5, 12, 3, 25, 8, 30]
strong = [lv for lv in levels if lv >= 10]
print(strong)How to read it
Let's keep reading the wrong way! Start with the `for` part: 'For each `lv` in the `levels`...'. Then, look at the `if` part: '...only include `lv` if `lv >= 10` is `True`.' Finally, look at the `expression`: '...apply `lv`.
Only elements where `lv >= 10` is `True` are included. The rest are skipped.
Exercise 8 — Filtered Comprehension
team = ["Aquachu", "Pyrochu", "Zap", "Florachu"]
short = [n for n in team if len(n) <= 5]
print(short)What is printed?
Hint : `len("Zap")` is 3, `len("Aquachu")` is 7. Which names have 5 or fewer characters?
Exercise 9 — Comprehension with Filter
Complete the code to get only Codémon with level above 20.
Hint : You need a keyword to iterate, and an operator to filter by level.
Exercise 10 — Expression + Filter
You can combine both — transform elements and filter them in the same comprehension.
levels = [5, 12, 3, 25, 8, 30]
boosted = [lv * 2 for lv in levels if lv >= 10]
print(boosted)Only levels >= 10 are kept, and those are doubled. This is like having a `for` loop with an `if` and an `append` — all in one line!
Exercise 11 — Combined Expression + Filter
nums = [1, 2, 3, 4, 5, 6]
result = [n * 10 for n in nums if n % 2 == 0]
print(result)What is printed?
Hint : `n % 2 == 0` checks if `n` is even. Only even numbers get multiplied by 10.
Exercise 12 — Comprehension to Result
Match each list comprehension to its output.
Exercise 13 — Codémon Team Builder
Using list comprehensions: 1. Given a list of Codémon with their levels, create a new list with only those level 20+ 2. After training, all their levels went up by 2! Create a list of all levels + 2 3. Print each list
team = [("Aquachu", 30), ("Pyrochu", 15), ("Florachu", 25), ("Zap", 8), ("Rockachu", 22)]
# 1. Filter: only level 20+
# 2. All levels + 2
# 3. Print each list