About 1545 letters
About 8 minutes
Comprehensions provide a concise syntax for creating containers.
For example, to create a list of length 10 with elements as x², we could use a loop:
numbers: list[int] = []
for x in range(10):
numbers.append(x**2)
print(numbers)
But this is a bit verbose. A comprehension makes it simpler:
# List comprehension
numbers: list[int] = [x**2 for x in range(10)]
print(numbers)
x**2
defines the value of each element for x in range(10)
assigns values to x
Comprehensions can also use nested loops, for example to generate a multiplication table:
# List comprehension
numbers: list[int] = [x*y for x in range(1, 10) for y in range(1, 10)]
print(numbers)
Sets and dictionaries can also be created with comprehensions:
# Set comprehension
numbers_set: set[int] = {x**2 for x in range(10)}
print(numbers_set)
# Dictionary comprehension
numbers_dict: dict[int] = {x: x**2 for x in range(10)}
print(numbers_dict)
Tuples do not support comprehensions directly, because parentheses ()
are used for generators. However, you can use the tuple() function to convert a generator into a tuple.
Generators will be discussed in a later section.
# Attempting a tuple comprehension
numbers: tuple[int] = (x**2 for x in range(10))
print(numbers)
print(tuple(numbers)) # Convert generator to tuple
Created in 5/15/2025
Updated in 5/21/2025