lint warnings
Duncan Booth
duncan.booth at invalid.invalid
Tue Feb 15 09:32:13 EST 2011
Gerald Britton <gerald.britton at gmail.com> wrote:
> I find:
>
> 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.
<snip>
> Also, as already shown, the map version is faster.
In most cases the list comprehension is faster. Try timing it.
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
map is only likely to be faster if you wanted to call a function in both cases.
If you have an expression that can be inlined you save the function call
overhead with the list comprehension.
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list