Python Comprehensions (Comprehensions)
Comprehensions are a very powerful and expressive syntactic sugar in Python, allowing you to create new lists, dictionaries, or sets from existing iterables (such as lists, tuples, sets, etc.) in a very concise way.
Using comprehensions not only makes code shorter and more readable, but is often faster than using traditional for loops.
List Comprehensions (List Comprehensions)
List comprehensions provide a compact syntax for creating lists.
Basic syntax:[expression for item in iterable]
Example: Create a list containing squares of 0 to 9
Traditional for loop approach:
squares = []
for x in range(10):
squares.append(x**2)
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Using list comprehension:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]List Comprehensions with Condition
You can add an if condition after the comprehension to filter elements.
Syntax:[expression for item in iterable if condition]
Example: Create a list containing only squares of even numbers
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # Output: [0, 4, 16, 36, 64]List Comprehensions with if-else
You can also use if-else in the expression part to determine element values based on conditions.
Syntax:[expression_if_true if condition else expression_if_false for item in iterable]
Example: Change odd numbers to negative, leave even numbers unchanged
numbers = [x if x % 2 == 0 else -x for x in range(10)]
print(numbers) # Output: [0, -1, 2, -3, 4, -5, 6, -7, 8, -9]Dictionary Comprehensions (Dictionary Comprehensions)
Similar to list comprehensions, dictionary comprehensions are used for quickly creating dictionaries.
Syntax:{key_expression: value_expression for item in iterable}
Example: Create a dictionary of numbers and their squares
square_dict = {x: x**2 for x in range(5)}
print(square_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Example: Create a dictionary from a list
fruits = ["apple", "banana", "cherry"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
print(fruit_lengths) # Output: {'apple': 5, 'banana': 6, 'cherry': 6}Set Comprehensions (Set Comprehensions)
The syntax for set comprehensions is almost identical to list comprehensions, but uses curly braces {}.
Syntax:{expression for item in iterable}
Example: Create a unique set of squares from a list with duplicate elements
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_squares = {x**2 for x in numbers}
print(unique_squares) # Output: {1, 4, 9, 16, 25}Comprehensions are an important part of Pythonic programming style. Mastering their use can significantly improve your coding efficiency and code quality.