Python’s map()
is a built-in function that executes a specified function on all the elements of an iterator and returns a map object (an iterator)
for retrieving the results. The elements are sent to the function as a parameter. An iterator, for example, can be a list, a tuple, a string, etc., and it returns an iterable map object.
Syntax of map function in python
The syntax for the map()
function is as follows:
Syntax: map(function, iterable[, iterable1, iterable2,.., iterableN])
Parameters :
• Function: A mandatory function that will be applied to all the elements of a given iterable.
• Iterable: It is iterable and must be mapped. It could be a list, a tuple and so on. Many iterator objects may be passed to the map()
function.
Return Value
The function map()
applies a given function to every element of an iterable and returns an iterable map object, i.e. a tuple, a list, etc.
Python map() example
Let’s write a function to be used with map()
function.
#function to square the value passed to it
def square(x): return x * x
It’s a simple function that returns the square of the input object.
#creating a list my_list = [1, 2, 3, 4, 5] result = map(square, my_list) #prints a list containing the square values print(result)
The map()
function takes the square function and my_list
iterable. Any element in my_list
is passed by map()
to square function.
The function will print iterator elements with white space.
Python map() Function Example Using a Lambda Function
The first argument for map()
is a function, which we use to apply to each element. For each aspect of the iterable, Python calls the function once and returns the manipulated element to a map object.
The syntax of map() with a lambda function is as follows:
map(lambda argument(s): expression)
We may implement a lambda function
for a list like below with an expression we would like to use for each object in our list:
n = [5, 10, 15, 20, 25, 30]
We may use map()
and lambda
to use an expression against any of our numbers.
mapped = list(map(lambda x: x * x, n))
We declare elements here as x in our list. And we multiply by the same element. We move our number list as the map()
iterable.
We print a listing of the map object to get the results immediately:
print(mapped)
Complete Program and output: