List Comprehension
List comprehension is one of the most commonly used types of comprehension in Python. It is used to create a new list from an existing one by applying a transformation to each element of the original list.
Syntax
new_list = [expression for items in iterable if condition]
Parameters
- Expression - is the operation to be performed on each element
- Item- is the variable representing each element of the iterable
- Iterable - is the existing(old) list
- Condition- is an optional condition that filters the elements of the iterable.
Example
Code in Python
list = [1, 2, 3, 4, 5, 6]
new_list = [i * 2 for i in list if i % 2 == 0]
print("The new list for [1, 2, 3, 4, 5, 6] is " , new_list)
Output
The new list for [1, 2, 3, 4, 5, 6] is [4, 8, 12]
In this code, we create a new list by multiplying each element of the original list by 2 if it is even. The `if` statement in the comprehension serves as a filter to select only even numbers from the original list.
Set Comprehension
In set comprehension, we use a set/list to create a new set by applying a transformation to each element of the original set.
Syntax
new_set = {expression for items in iterable if condition}
Parameters
- Expression - is the operation to be performed on each element
- Item- is the variable representing each element of the iterable
- Iterable - is the existing(old) list
- Condition- is an optional condition that filters the elements of the iterable.
Example
Code in Python
old_list = [1, 2, 3, 4, 5, 6]
new_set = {x for x in old_list if x % 2 == 0}
print("The new set for [1, 2, 3, 4, 5, 6] is " , new_set)
Output
The new set for [1, 2, 3, 4, 5, 6] is {2, 4, 6}
In this code, we create a new set of even numbers by checking if the number in the existing list is even. The `if` statement in the comprehension serves as a filter to select only even numbers from the original set.
Check out this article - Swapcase in Python and Convert String to List Python.
Dictionary Comprehension
Dictionary comprehension is used to create a new dictionary from an existing one by applying a transformation to each key-value pair of the original dictionary.
Syntax
new_set = {expression for items in iterable if condition}
Parameters
- Key_expression - is the operation to be performed on each key
- value_expression - is the operation to be performed on each value
- key and value - are the variables representing each key-value pair of the iterable
- Iterable - is the existing dictionary
- condition - is an optional condition that filters the key-value pairs
Example
Code in Python
dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
new_dict = {k: v * 2 for k, v in dict.items() if v % 2 == 0}
print("The new dictionary for {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} is ", new_dict)
Output
The new dictionary for {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} is {'b’: 4, 'd': 8}
In this code, we create a new dictionary by multiplying the value of each key-value pair of the original dictionary by 2 if the value is even. The `if` statement in the comprehension serves as a filter to select only key-value pairs with even values from the original dictionary.
Generator Comprehension
Generator comprehension is another type of Python comprehension that works similarly to list comprehension and set comprehension, but it creates a generator object instead of a list or set.
A generator object is iterable that generates its values on-the-fly, rather than storing them all in memory at once. This is useful for working with large datasets, as it allows you to process them lazily and incrementally rather than loading everything into memory at once.
Syntax
new_generator = (expression for items in iterable if condition)
Parameters
- Expression - is the operation to be performed on each element
- Item- is the variable representing each element of the iterable
- Iterable - is the existing(old) list
- Condition- is an optional condition that filters the elements of the iterable.
Example
Code in Python
old_list = [1, 2, 3, 4, 5, 6]
new_generator = (x**2 for x in old_list if x % 2 == 0)
print("The new generator for [1, 2, 3, 4, 5] is ")
for val in new_generator:
print(val)
Output
The new generator for [1, 2, 3, 4, 5] is
4
16
36
In this code, we create a new generator object using generator comprehension, which generates the squares of the even numbers in the old list. The `if` statement in the comprehension serves as a filter to select only even numbers from the original list.
Nested Comprehension
Nested comprehension is a technique where we use one or more comprehension statements inside another comprehension statement. It allows us to create complex data structures like lists of lists, sets of tuples, and dictionaries of lists.
Example
Code in Python
# create a list of tuples from two existing lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = [(x, y) for x in list1 for y in list2 if x + y > 7]
print("The new list of list is " ,new_list)
Output
The new list of list is [(2, 6), (3, 5), (3, 6)]
In this code, we create a new list of tuples using nested comprehension. The expression (x, y) creates a tuple with two elements, x, and y.
The first `for` loop iterates over each element in list1, and the second `for` loop iterates over each element in list2. The `if` condition filters out tuples whose elements sum up to less than or equal to 7.
Nested comprehension can be used with any comprehension statement: list comprehension, set comprehension, dictionary comprehension, or generator comprehension.
However, it's important to remember that nesting too many comprehension statements can lead to unreadable and inefficient code. It's usually better to use nested comprehension when it improves the conciseness and clarity of the code.
Frequently Asked Questions
What are the benefits of using comprehension in Python?
The benefits of using Python comprehension include reducing the amount of code needed to create a new data structure, improving the readability of the code, and making the code more efficient.
Can comprehension be used with nested data structures in Python?
Yes, comprehension can be used with nested data structures in Python. For example, you can create a new list of tuples by applying a transformation to each element of a nested list.
Which is better, list comprehension or lambda function?
List comprehension seems to be better than the lambda function as with the lambda function, and you have to use the `map` function usage of which results in a function call for each element, whereas the list comprehension compiles it into a single loop that builds the list which has better readability as well.
Conclusion
In conclusion, Python comprehension provides a powerful and concise way to create collections from other iterables. By mastering the different types of comprehension and understanding their best use cases, you can write more efficient, readable, and elegant Python code.