Python Map Function Tutorial (Simple Guide)

0
127
map function

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:

map(function, sequence)

Say you have a function:

def square(n):

return n**2

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.

l= [1,2,3,4]

Using map  will apply the function to all items in the sequence.

map (square, l)

will output:

[1,4,9,16]

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

l= [1,2,3,4]

v=[5,6,7,8]

We can do a function across the lists:

map(lambda x,y: x*y, l,v)

which will output:

[5,12,21,32]

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.

Map is very powerful when used together with reduce and filter functions.

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:

https://docs.python.org/2/tutorial/datastructures.html

LEAVE A REPLY

Please enter your comment!
Please enter your name here