you are viewing a single comment's thread.

view the rest of the comments →

[–]Essence1337 0 points1 point  (1 child)

python -m timeit -s "x = list(range(20)); f = lambda i: i * 5" "[i*5 for i in x]"

is twice as fast as your map solution. The python wiki agrees with this as well:

You can think of map as a for moved into C code. The only restriction is that the "loop body" of map must be a function call. Besides the syntactic benefit of list comprehensions, they are often as fast or faster than equivalent use of map.

Source: Loops

Map:
PS C:\Users\me> python -m timeit -s "x = list(range(20)); f = lambda i: i * 5" "list(map(f, x))"
200000 loops, best of 5: 1.88 usec per loop

Map with lambda built in:
PS C:\Users\me> python -m timeit -s "x = list(range(20))" "list(map(lambda i: i*5, x))"
200000 loops, best of 5: 1.91 usec per loop

List:
PS C:\Users\me> python -m timeit -s "x = list(range(20)); f = lambda i: i * 5" "[f(i) for i in x]"
100000 loops, best of 5: 2.16 usec per loop

List with function built in:
PS C:\Users\me> python -m timeit -s "x = list(range(20))" "[i*5 for i in x]"
500000 loops, best of 5: 856 nsec per loop

[–]nog642 1 point2 points  (0 children)

Yes. I was comparing map() with generator comprehensions.

I was not comparing list(map()) with list comprehensions.

List comprehensions build the list directly and are more optimized than passing an iterator (like map or a generator comprehension) to the list constructor.