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
# create two sample lists lst1 and lst2 as shown lst1 = [ 10 , 20 , 30 ] lst2 = [ 3 , 4 , 5 ] # this empty list stores the output result = [] # Now, run a nested for loop # add every element of the lst1 to all elements of lst2 # store the output in a separate list for i in lst1: for j in lst2: result.append(i + j) # print the result 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
# create two sample lists lst1 and lst2 as shown lst1 = [ 10 , 20 , 30 ] lst2 = [ 3 , 4 , 5 ] # this empty list stores the output result = [] # now, apply nested map function on both the # created lists append the final output to # the "result" list 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.