Lesson 31/48 ยท ๐ฆ Data Structures
๐ฆ Data StructuresLesson 31/48
Phase 5 ยท Data Structures20 min
List Comprehensions
The Pythonic one-liner that replaces a for loop, elegant and fast
You've been writing loops that build lists item by item. List comprehensions let you express the same logic in a single readable line, and they're considered the "Pythonic" way to do it.
How would you approach this? Think first, then expand.
Loop vs list comprehensionpython
# The loop way
squares = []
for n in range(1, 6):
squares.append(n ** 2)
print(squares) # [1, 4, 9, 16, 25]
# The list comprehension way
squares = [n ** 2 for n in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]Read it like English: "Give me n squared, for every n in range(1, 6)".
Syntax:
Syntax:
[expression for variable in iterable]Adding a filter condition
Put an
Put an
if at the end to only include items that match:List comprehension with conditionpython
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Only even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Words longer than 3 letters
words = ["hi", "hello", "yo", "world", "a"]
long_words = [w for w in words if len(w) > 3]
print(long_words) # ['hello', 'world']๐คQuick Check
What does [x * 2 for x in [1, 2, 3]] produce?
Transforming strings
String transformationspython
names = ["alice", "bob", "charlie"]
# Capitalise all names
proper = [name.title() for name in names]
print(proper) # ['Alice', 'Bob', 'Charlie']
# Get first letters
initials = [name[0].upper() for name in names]
print(initials) # ['A', 'B', 'C']Dictionary comprehensions, same idea, for dicts
Dict comprehensionpython
# Square each number and store as {n: n^2}
squares = {n: n ** 2 for n in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Flip a dictionary (values become keys, keys become values)
original = {"a": 1, "b": 2, "c": 3}
flipped = {v: k for k, v in original.items()}
print(flipped) # {1: 'a', 2: 'b', 3: 'c'}๐คQuick Check
Which produces only the uppercase words from ["Hello", "world", "Python"]?
๐In the Real World...
Filter running pods: [p for p in pods if p.status == "Running"]. Get all image names: [c.image for c in pod.spec.containers]. List comprehensions read like English and that's intentional.
Practice Exercises
0/3 solvedExercise 1 of 3easy
โฑ 00:00Celsius to Fahrenheit
Convert a list of Celsius temperatures to Fahrenheit using a list comprehension.
Formula: F = C * 9/5 + 32
Given: temps_c = [0, 20, 37, 100]Expected output:
Formula: F = C * 9/5 + 32
Given: temps_c = [0, 20, 37, 100]Expected output:
[32.0, 68.0, 98.6, 212.0]solution.py
1 / 3
Exercise 2 of 3easy
โฑ 00:00Even Squares
Using a list comprehension with a condition, build a list of squares of all even numbers from 1โ20.
Expected output:
Expected output:
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]solution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00Word Length Dict
Build a dictionary mapping each word to its length using a dict comprehension.
Given: words = ["python", "is", "awesome"]Expected output:
Given: words = ["python", "is", "awesome"]Expected output:
{'python': 6, 'is': 2, 'awesome': 7}solution.py
3 / 3
Solve all 3 exercises to unlock completion