Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: List Comprehensions vs. map

Referring to this Python List Comprehension Vs. Map question, can someone explain why List Comprehensions gives better results over map when list comprehension does not call a function, even when there is no lambda function in the map but gives the worst result when calling a function?

import timeit

print timeit.Timer('''[i**2 for i in xrange(100)]''').timeit(number = 100000)

print timeit.Timer('''map(lambda i: i**2, xrange(100))''').timeit(number = 100000)

print timeit.Timer(setup="""def my_pow(i):
    return i**2
""",stmt="""map(my_pow, xrange(100))""").timeit(number = 100000)

print timeit.Timer(setup="""def my_pow(i):
    return i**2
""",stmt='''[my_pow(i) for i in xrange(100)]''').timeit(number = 100000)

results:

1.03697046805 <-- list comprehension without function call
1.96599485313 <-- map with lambda function
1.92951520483 <-- map with function call
2.23419570042 <-- list comprehension with function call
like image 562
zenpoy Avatar asked Jul 23 '12 16:07

zenpoy


People also ask

Is map faster than list comprehension in Python?

Map function is faster than list comprehension when the formula is already defined as a function earlier. So, that map function is used without lambda expression.

Which is better list comprehension or map?

List comprehension is more concise and easier to read as compared to map. List comprehension are used when a list of results is required as map only returns a map object and does not return any list. Map is faster in case of calling an already defined function (as no lambda is required).

Is map better than for loop Python?

map() works way faster than for loop. Considering the same code above when run in this ide.

Are list comprehensions more efficient?

Conclusions. List comprehensions are often not only more readable but also faster than using “for loops.” They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.


1 Answers

All your timing results can be explained by theses facts:

  1. CPython has a rather high function call overhead.

  2. map(f, it) is slightly faster than [f(x) for x in it].

The first version of your code does not define a function at all, so there is no function call overhead. The second version needs to define a function, ,so there is function call overhead in every iteration. The third version is completely equivalent to the second one – functions and lambda expressions are the same thing. And the last version is even slower according to fact 2.

like image 128
Sven Marnach Avatar answered Sep 20 '22 22:09

Sven Marnach