In the previous post, we discussed main ideas around list comprehension. We will continue to extend the ideas in this post.
Let's create a list of lists first.
list_of_lists = [ [ 1,2,3,4], [4,5,6], [7,8,9] ]
Flattening list of lists -the Usual Way .
list_flatten = [ ]
for element_list in list_of_lists:
for element in element_list:
list_flatten.append(element)
print(list_flatten)
---> [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]
Flatten List using List Comprehension.
list_flatten_comprehension =[ element for element_list in list_of_lists for element in element_list]
print(list_flatten_comprehension)
--->[1, 2, 3, 4, 4, 5, 6, 7, 8, 9]
Beginners in Python tend to make one mistake (At least I used to make it often).
Name Error while using List Comprehension.
What would happen if you write list comprehension as below?
list_flatten_comprehension = [element for element in element_list for element_list in list_of_lists]
---> NameError: name 'element_list' is not defined
You get a NameError stating element_list is not defined. What happens is, the Python Interpreter tries to iterate through the elements in the element_list. Unfortunately , element_list is only defined in the second for loop. Hence, Python gives a NameError as it cannot find the definition of element_list in the first for loop.
In the next post, we will extend the ideas of list comprehension to other Python data structures.
Comments
Post a Comment