Python List Comprehension
List comprehension is nothing but writing the logic on the python lists in a brief or short way.Lets start with an example,
# Here is the code snippet to find the square of each item in the list # Append to the new list l_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_list = [] for each_item in l_list: new_list.append(each_item ** 2) print(new_list)
l_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_list = [each_item ** 2 for each_item in l_list] print(new_list) # Using Python list comprehension the no of lines of code is reduced from 3 to 1.
In the above picture,
- Step1 represents the new list creation
- Step2 represents placing the for loop in to comprehensive way
- Step3 represents placing the square of the each item into the list
Lets see another example, finding the positive numbers in a given list.
# Here is the code snippet to find the squares of numbers in the list # Append to the new list l_list = [[1, 2, 3], [-1, 0, 1], [2, -4, 2]] new_list = [] for sub_list in l_list: temp = [] for item in sub_list: if item > 0: temp.append(item) new_list.append(temp) print(new_list)
l_list = [[1, 2, 3], [-1, 0, 1], [2, -4, 2]] new_list = [[item for item in sub_list if item > 0] for sub_list in l_list] print(new_list)
In the above example, it is clearly shown how two for loops are merged into a single line using Python list comprehension.
Some points on Python list comprehension:
- Concise and shorter code
- Python list comprehension can used
- To make a new list where each element is the result after a certain operation
- To make a sub list after checking some condition on each item of the list
- All the logics on list can not be comprehended
- Python list comprehensions are not readable or understandable for beginners
- Its your choice to use Python list comprehension or not. Not mandatory to use.
Comments
Post a Comment