The map function is a very helpful tool to use where you need to apply an operation to items of a sequence (e.g. list, tuples, etc.)
It takes the form:
Say you have a function:
If you run this function using an input of 2, square(2), you will get an output of 4.
How is map useful? For example you want to run the square function on an items within a sequence.
Using map will apply the function to all items in the sequence.
map (square, l)
I know this is a very simple example but imagine if you really have a really complicated function that you need to apply on a list. That is when you will fully appreciate the map function.
Also in practice, functions are not usually defined first before using map. The lambda expression is more commonly used.
map(lambda x: x**2,l)
This is done usually for one time quick use with the purpose of saving time.
Another practical use of map is when you need to do operations across multiple sequences.
Lambda allows the map to take multiple arguments.
For example let’s introduce another list called v
We can do a function across the lists:
map(lambda x,y: x*y, l,v)
which will output:
So you would not need to define a function before using map function.
This is made possible by lambda being able to take multiple arguments.
Amazing huh? Go and explore map function on your own and apply to more complicated problems.
So that is it for map function quick guide.
For more information go to the official python documentation: