Comprehensions in Python
Comprehensions in Python
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:
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.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
res = [num for num in a if num % 2 == 0]
print(res)
Output
[2, 4, 6, 8]
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
Output
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:
Where:
key_expression: Determines the dictionary key.
value_expression: Computes the value.
iterable: The source collection.
condition (optional): Filters elements before adding them.
Output
Explanation: This creates a dictionary where keys are numbers from 1 to 5 and
values are their cubes.
Example 2: Mapping states to capitals
Output
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.
a = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]
Output
{2, 4, 6}
Output
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:
Output
[0, 2, 4, 6, 8]
Explanation: This generator produces even numbers from 0 to 9, but values are only
computed when accessed.
Example 2: Generating squares using a generator
Output
Explanation: The generator creates squared values on demand and returns them as
a tuple when converted.