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
We can also convert a map object to sequence objects such as list, tuple, etc.
The syntax is as follows:
Now let’s take a look at an example of an implementation of the
#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:
Let’s convert the map object above to
#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
View all Courses