#Python's comprehensions
Comprehensions provide a concise syntax for creating containers.
#List Comprehension
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)
- The expression
x**2
defines the value of each element - The loop
for x in range(10)
assigns values tox
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)
#Set and Dictionary Comprehensions
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)
#Tuple Comprehension
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