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
zenpoy
source share