Comprehensions in Python provide a concise and efficient way to create new sequences from existing ones. 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 1: Generating a list of even numbers
Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
res = [num for num in a if num % 2 == 0]
print(res)
Explanation: This creates a list of even numbers by filtering elements from a that are divisible by 2.
Example 2: Creating a list of squares
Python
res = [num**2 for num in range(1, 6)]
print(res)
Explanation: This generates a list of squares for numbers from 1 to 5.
Dictionary comprehension
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 1: Creating a dictionary of numbers and their cubes
Python
res = {num: num**3 for num in range(1, 6)}
print(res)
Output{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
Explanation: This creates a dictionary where keys are numbers from 1 to 5 and values are their cubes.
Example 2: Mapping states to capitals
Python
a = ["Texas", "California", "Florida"] # states
b = ["Austin", "Sacramento", "Tallahassee"] # capital
res = {state: capital for state, capital in zip(a, b)}
print(res)
Output{'Texas': 'Austin', 'California': 'Sacramento', 'Florida': 'Tallahassee'}
Explanation: zip() function pairs each state with its corresponding capital, creating a dictionary.
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: The operation applied to each item.
- iterable: The source collection.
- condition (optional): Filters elements before adding them.
Example 1: Extracting unique even numbers
Python
a = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]
res = {num for num in a if num % 2 == 0}
print(res)
Explanation: This creates a set of even numbers from a, automatically removing duplicates.
Example 2: Creating a set of squared values
Python
res = {num**2 for num in range(1, 6)}
print(res)
Explanation: This generates a set of squares, ensuring each value appears only once.
Generator comprehensions
Generator Comprehensions create iterators that generate values lazily, making them memory-efficient as elements are computed only when accessed.
Syntax:
(expression for item in iterable if condition)
Where:
- expression: Operation applied to each item.
- iterable: The source collection.
- condition (optional): Filters elements before including them.
Example 1: Generating even numbers using a generator
Python
res = (num for num in range(10) if num % 2 == 0)
print(list(res))
Explanation: This generator produces even numbers from 0 to 9, but values are only computed when accessed.
Example 2: Generating squares using a generator
Python
res = (num**2 for num in range(1, 6))
print(tuple(res))
Explanation: The generator creates squared values on demand and returns them as a tuple when converted.
Similar Reads
List Comprehension in Python List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
List Comprehension in Python List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
List Comprehension in Python List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
List Comprehension in Python List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
List Comprehension in Python List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read