[]
Introduction
We can use the Python built-in function map() to apply a function to each item in an iterable (like a list or dictionary) and return a new iterator for retrieving the results. map() returns a map object (an iterator), which we can use in other parts of our program. We can also pass the map object to the list() function, or another sequence type, to create an iterable.
The syntax for the map() function is as follows:
map(function, iterable, [iterable 2, iterable 3, …])
Instead of using a for loop, the map() function provides a way of applying a function to every item in an iterable. Therefore it can often be more performant since it is only applying the function one item at a time rather than making copies of the items into another iterable. This is particularly useful when working on programs processing large data sets. map() can also take multiple iterables as arguments to the function by sending one item from each iterable to the function at a time.
In this tutorial, we’ll review three different ways of working with map(): with a lambda function, with a user-defined function, and finally with a built-in function using multiple iterable arguments.
The first argument to map() is a function, which we use to apply to each item. Python calls the function once for every item in the iterable we pass into map() and it returns the manipulated item within a map object. For the first function argument, we can either pass a user-defined function or we can make use of lambda functions, particularly when the expression is less complex.
The syntax of map() with a lambda function is as follows:
map(lambda item: item[] expression, iterable)
With a list like the following, we can implement a lambda function with an expression that we want to apply to each item in our list:
numbers = [10, 15, 21, 33, 42, 55]
To apply an expression against each of our numbers, we can use map() and lambda:
mapped_numbers = list(map(lambda x: x * 2 + 3, numbers))
Here we declare an item in our list as x. Then we add our expression. We pass in our list of numbers as the iterable for map().
In order to receive the results of this immediately we print a list of the map object:
print(mapped_numbers)
Output
[23, 33, 45, 69, 87, 113]
We have used list() so that the map object is returned to us as a list, rather than a less human-readable object like: