Python

map

Map takes a function and applies it to every element of the collection. It then returns a new collection.

To get map() to return a list in Python 3.x, you need to cast it with list().

Related course: Data Science and Machine Learning with Python – Hands On!

Map example

The method is roughly:

 
map(function,list)


and in Python 3 its equivalent to:
 
def map(func, iterable):
for i in iterable:
yield func(i)


so how do you use it?

Given a simple list, we can apply a function to it:

 
xs= [1,2,3,4,5,6,7,8]

def f(x):
return (x * 2)

ys = list(map(f,xs))
print(ys)

This will output:


[2, 4, 6, 8, 10, 12, 14, 16]

We can also use lambda with map:

 
xs= [1,2,3,4,5,6,7,8]
ys = map(lambda x: x * 2, xs)
print(list(ys))


which gives us the same output.

Map vs list comprehensions

Map isn’t unique to Python and you can achieve the same with list comprehensions.

 
map(f, iterable)


can be written as:
 
[f(x) for x in iterable]


In most of the cases you want to use list comprehensions, because other software developers will easily read your code.

If you want to compare speed, open the terminal and write:


$ python -mtimeit -s’x1=range(100)’ ‘[hex(x) for x in x1]’
$ python -mtimeit -s’x1=range(100)’ ‘map(hex, x1)’

 

Previous Post Next Post

Cookie policy | Privacy policy | ©