lint warnings
Gerald Britton
gerald.britton at gmail.com
Tue Feb 15 10:19:20 EST 2011
>> 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.
not necessarily, no.
>>> [-i if i < 0 else i for i in range(-10,0)]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
vs.
>>> map(abs, range(-10,0))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
<snip>
> 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.
--
Gerald Britton
More information about the Python-list
mailing list