Python - map() Function
map() function applies the specified function to every item of the passed iterable, yields the results, and returns an iterator.
map(function, iterables) --> map object
- function: The function to be called for each element of the specified iterable.
- iterables: One or more iterables separated by a comma (such as string, list, tuple, dictionary).
Returns an iterator object of the
Consider the following simple square function.
def square(x): return x*x
Now, we can call the map function with the list of numbers to get the list of results, as shown below.
>>> numbers=[1, 2, 3, 4, 5] >>> sqrs_of_numbers=map(square, numbers) >>> next(sqrs_of_numbers) 1 >>> next(sqrs_of_numbers) 4 >>> next(sqrs_of_numbers) 9 >>> next(sqrs_of_numbers) 16 >>> next(sqrs_of_numbers) 25
In the above example, the
map() function applies to each element in the
This will return an object of the
map class, which is an iterator, and so, we can use the next() function to traverse the list.
Map with Lambda Expression
map() function passes each element in the list to the built-in functions, a lambda function, or a user-defined function, and returns the mapped object.
map() is used with the lambda function.
>>> sqrs_of_numbers = map(lambda x: x*x, [1, 2, 3, 4]) >>> next(sqrs_of_numbers) 1 >>> next(sqrs_of_numbers) 4 >>> next(sqrs_of_numbers) 9 >>> next(sqrs_of_numbers) 16 >>> next(sqrs_of_numbers) 25
Map with Built-in Function
In the following example, a built-in function pow() is given to map two list objects, one for each base and index parameter. The result is a list containing the power of each number in bases raised to the corresponding number in the index.
>>> bases=[10, 20, 30, 40, 50] >>> index=[1, 2, 3, 4, 5] >>> powers=list(map(pow, bases, index)) >>> powers [10, 400, 27000, 2560000, 312500000]