The map function accepts multiple iterables. These can be passed in as optional arguments. If multiple iterables are passed in, an element from each is passed in as an argument to the designated function.
Assume we have the following lists:
l1 = [1, 2, 3, 4, 5]
l2 = [11, 12, 13, 14, 15]
l3 = [21, 22, 23, 24, 25]
With map we can create a new list that contains the addition of elements at each index. So in our resulting list at index 0, we will have the sum of l1, l2, and l3. This will continue for each element in the list.
In order for this to work, the function we pass in must take the same number of arguments as the number of iterables you pass in. So if you pass in three lists, your function must take three arguments.
Let's create our function:
def add_three_numbers(num1, num2, num3):
return num1 + num2 + num3
Now that we have our function we can use map to generate our desired list:
map(add_three_numbers, l1, l2, l3)
This will produce:
[33, 36, 39, 42, 45]
You may have noticed that each of our lists has exactly five elements. So the map function worked very nicely. Its important to note how map handles iterables of different sizes. This is where Python 2 and Python 3 are different.
Python 2 will iterate through the longest iterable and pass None in as the argument of the short iterables. So if one list has a length of seven and another list has a length of five, map will iterate through seven times but pass in None for the indices of the shorter list that exceed its length. If this is a possibility, your function must be prepared to handle arguments of NoneType (ours would throw a TypeError).
Python 3 is a much cleaner implementation. It will only iterate through the length of the shortest iterable. So if you have a list of seven and a list of five, it will only iterate through five times.
Read more about Python 2 map
Read more about Python 3 map
Did you know Python has its own zip/unzip function? Check out our guide to learn how to use the Python Zip and Unzip Function.