G
Gerald Britton
I find:
not necessarily, no.
vs.
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
I have as have many others (including the previous poster who provided timings)
C:\Python27>python.exe lib\timeit.py -s "def double(x): return x*2" -s
"data=range(10000)" "[x*2 for x in data]"
1000 loops, best of 3: 879 usec per loop
granted, but not on topic here. we're talking about map vs list comps
when you want to use a function.
Which is exactly the point.
Of course, but that's not the point.
map(func, iterable)
to be "neater" than:
[func(item) for item in iterable]
If nothing else, the "map" version is shorter.
That's only true if you wanted to call an existing function. If you wanted
to do something involving a more complex expression that you can write
inline then the list comprehension is shorter.
not necessarily, no.
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1][-i if i < 0 else i for i in range(-10,0)]
vs.
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Also, as already shown, the map version is faster.
In most cases the list comprehension is faster. Try timing it.
I have as have many others (including the previous poster who provided timings)
C:\Python27>python.exe lib\timeit.py -s "def double(x): return x*2" -s "data=range(10000)" "map(double, data)"
1000 loops, best of 3: 1.82 msec per loop
C:\Python27>python.exe lib\timeit.py -s "def double(x): return x*2" -s
"data=range(10000)" "[x*2 for x in data]"
1000 loops, best of 3: 879 usec per loop
granted, but not on topic here. we're talking about map vs list comps
when you want to use a function.
map is only likely to be faster if you wanted to call a function in both cases.
Which is exactly the point.
f you have an expression that can be inlined you save the function call
overhead with the list comprehension.
Of course, but that's not the point.