Comprehensions provide a concise way to create collections (like lists, dictionaries, sets, and even generators) from existing iterables. They can make the code more readable and compact.
There are three main types of comprehensions in Python:
List comprehensions are used to create new lists by applying an expression to each element in an existing iterable.
Syntax:
[expression for item in iterable if condition]
Example:
# Create a list of squares
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example with Condition:
# Create a list of even squares
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # Output: [0, 4, 16, 36, 64]
Dictionary comprehensions are used to create dictionaries from existing iterables.
Syntax:
{key_expression: value_expression for item in iterable if condition}
Example:
# Create a dictionary mapping numbers to their squares
squares_dict = {x: x**2 for x in range(10)}
print(squares_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Example with Condition:
# Create a dictionary mapping even numbers to their squares
even_squares_dict = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares_dict) # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Set comprehensions are used to create sets from existing iterables.
Syntax:
{expression for item in iterable if condition}
Example:
# Create a set of squares
squares_set = {x**2 for x in range(10)}
print(squares_set) # Output: {0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
Example with Condition:
# Create a set of even squares
even_squares_set = {x**2 for x in range(10) if x % 2 == 0}
print(even_squares_set) # Output: {0, 64, 4, 36, 16}