Convert a nested for loop to a map equivalent in Python
Last Updated :
27 Dec, 2021
In this article, let us see how to convert a nested for loop to a map equivalent in python.
A nested for loop’s map equivalent does the same job as the for loop but in a single line. A map equivalent is more efficient than that of a nested for loop. A for loop can be stopped intermittently but the map function cannot be stopped in between.
Syntax:
map(function, iterable).
This can be elaborated as
map(lambda x : expression, iterable)
Map function simply applies the specified function on the given iterable and returns the modified iterable as the result.
Example: Creating a nested loop
Python3
lst1 = [ 10 , 20 , 30 ]
lst2 = [ 3 , 4 , 5 ]
result = []
for i in lst1:
for j in lst2:
result.append(i + j)
print (result)
|
Output:
[13, 14, 15, 23, 24, 25, 33, 34, 35]
Now, let us look into the map equivalent of this nested for loop.
For this three map functions are used, two nested into the other. The first map function is the parent map function that joins the results of the inner two map functions. We have to pass the entire result to list() function. If we choose to ignore, the outermost list() function, the output will be a map object. The reason is that the map object doesn’t like to store the whole size of the iterable in its memory. So, to access the output, we would require to explicitly specify the output format of this map function to be a list.
Example: Convert a nested for loop to a map equivalent
Python3
lst1 = [ 10 , 20 , 30 ]
lst2 = [ 3 , 4 , 5 ]
result = []
list ( map ( lambda a: result.extend( map (a, lst2)),
map ( lambda a: lambda b: a + b, lst1)))
print (result)
|
Output:
[13, 14, 15, 23, 24, 25, 33, 34, 35]
If you compare the result of the nested for loop and its map equivalent, both are going to be the same. However, in time complexity, the map equivalent outperforms the nested for loop.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...