possibly trivial newbie list/array question
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu Aug 23 09:27:52 EDT 2001
Paul Rubin <phr-n2001 at nightsong.com> wrote in
news:7xy9obovj8.fsf at ruckus.brouhaha.com:
> Can you tell me the actual purpose of list comprehension?
>
> [f(x) for x in a]
>
> just seems like confusing syntactic hair that's otherwise equivalent
> to, though as we've seen sometimes slower than,
>
> map(lambda x: f(x), a).
Which would be much better written, and faster should it matter, as:
map(f, a)
>
> Am I missing something? Unless there's more to it than I see (which
> is quite possible), I don't understand why this feature made it into
> the language.
>
Once you get used to it it feels much cleaner and easier to read than the
lambda equivalent and less error prone as well. Would you care to rewrite
the following using map, filter and lambda?
[ f(x, y) for x in a for y in b if g(x,y) ]
As far as speed is concerned, you will find it very difficult in general to
predict whether the map or the list builder notation will be faster, and by
the time you have worked it out you will almost certainly have wasted more
time than you will ever save. Dont try to do micro-optimisations. Wait
until your code really is too slow then optimise the bits that matter.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list