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().

The method is roughly:

and in Python 3 its equivalent to:

so how do you use it?

Map example

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

This will output:

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

We can also use lambda with map:

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.

can be written as:

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

Leave a Reply