How to use the map function in Python

Python map takes a function and an iterable, and returns a map object and an iterator, which applies the function to all the elements in the iterable.

Note: You can pass more than one iterable to the map() function.

We can also convert a map object to sequence objects such as list, tuple, etc.

Syntax

The syntax is as follows:

Example

Now let’s take a look at an example of an implementation of the map() function.

#function to double the value passed to it
def doubler(x):
return x * 2
#creating a list
my_list = [1, 3, 5, 2, 4]
#map function takes the function doubler and the iterable my_list
#map will pass each element of my_list to doubler function
result = map(doubler, my_list)
#prints a list containing the doubled values
print(result)

The illustration below explains the example above:

1 of 6

Let’s convert the map object above to set type.

#converting map object to set
#result here is the final answer we got in the above code
result = [2, 6, 10, 4, 8]
print ("Converting to set")
answer1 = set(result)
print(answer1)

When you run the code above, the output will be displayed as a set instead of a list.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved