Lesson 9 of 15
Comprehensions
Comprehensions
Comprehensions are a concise, Pythonic way to build collections from iterables.
List Comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Dict Comprehension
words = ["hello", "world", "python"]
lengths = {w: len(w) for w in words}
# {'hello': 5, 'world': 5, 'python': 6}
Set Comprehension
A set is an unordered collection of unique elements. Using {} with a comprehension builds a set instead of a list — duplicates are automatically removed. Sets also support operations like | (union), & (intersection), and - (difference).
unique_lens = {len(w) for w in words}
# {5, 6}
Nested Comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
When to Use
Comprehensions shine for simple transformations and filters. For complex logic, a regular for loop is more readable.
Your Task
Implement primes_up_to(n) that returns a sorted list of all prime numbers from 2 to n (inclusive), using a list comprehension with a helper or direct logic.
Pyodide loading...
Loading...
Click "Run" to execute your code.