Python: list of concepts versus map

Citing this is Python List Comprehension Vs. Map , can anyone explain why List Comprehensions gives better results than map , when list comprehension does not call a function, even if map does not have a lambda function, but gives a worse 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 
+7
source share
1 answer

All your time results can be explained by facts:

  • CPython has a rather high load on functions.

  • map(f, it) 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 overhead for functional calls. The second version should define the function, so at each iteration there is an overhead of functions. The third version is completely equivalent to the second - functions and lambda expressions are one and the same. And the latest version is even slower according to fact 2.

+10
source

All Articles