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.
The syntax is as follows:
Now let’s take a look at an example of an implementation of the map()
function.
#function to double the value passed to itdef doubler(x):return x * 2#creating a listmy_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 functionresult = map(doubler, my_list)#prints a list containing the doubled valuesprint(result)
The illustration below explains the example above:
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 coderesult = [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