Comprehensions in Python provide a concise and efficient way to create new sequences from existing iterables using a single line of code. They enhance code readability and reduce the need for lengthy loops. Python supports four types of comprehensions:
- List Comprehensions
- Dictionary Comprehensions
- Set Comprehensions
- Generator Comprehensions
List comprehensions
List comprehensions allow for the creation of lists in a single line, improving efficiency and readability. They follow a specific pattern to transform or filter data from an existing iterable.
Syntax:
[expression for item in iterable if condition]
Where:
- expression: Operation applied to each item
- item: Variable representing the element from the iterable
- iterable: The source collection
- condition (optional): A filter to include only specific items
Example
The below list comprehension generates a list of even numbers.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
res = [num for num in a if num % 2 == 0]
print(res)
[2, 4, 6, 8]
Dictionary comprehensions
Dictionary Comprehensions are used to construct dictionaries in a compact form, making it easy to generate key-value pairs dynamically based on an iterable.
Syntax:
{key_expression: value_expression for item in iterable if condition}
Where:
- key_expression: Determines the dictionary key
- value_expression: Computes the value
- iterable: The source collection
- condition (optional): Filters elements before adding them
Example
Creating a dictionary of numbers and their cubes.
res = {num: num**3 for num in range(1, 6)}
print(res)
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
Set comprehensions
Set Comprehensions are similar to list comprehensions but result in sets, automatically eliminating duplicate values while maintaining a concise syntax.
Syntax:
{expression for item in iterable if condition}
Where:
- expression: Operation applied to each item
- item: Variable representing the element from the iterable
- iterable: The source collection
- condition (optional): Filters elements before adding them
Example
Extracting unique even numbers.
a = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]
res = {num for num in a if num % 2 == 0}
print(res)
{2, 4, 6}
Back to parent page: Python
Python Comprehensions List_Comprehensions Set_Comprehensions Dictionary_Comprehensions
Reference