more pythonic
Paul McGuire
ptmcg at austin.rr.com
Fri Feb 29 22:14:44 EST 2008
On Feb 29, 5:57 pm, Alan Isaac <ais... at american.edu> wrote:
> Paul McGuire wrote:
> > In general, whenever you have:
> > someNewList = []
> > for smthg in someSequence:
> > if condition(smthg):
> > someNewList.append( elementDerivedFrom(smthg) )
> > replace it with:
> > someNewList = [ elementDerivedFrom(smthg)
> > for smthg in someSequence
> > if condition(smthg) ]
>
> What is the gain? (Real question.)
>
> I think the first is often easier to read.
>
> Is the second more efficient?
>
> Also, I think list comprehensions are often easier to read
>
> as equivalent generator expressions:
>
> someNewList = list( elementDerivedFrom(smthg)
>
> for smthg in someSequence
>
> if condition(smthg) )
>
> Tastes vary of course.
>
> Cheers,
>
> Alan Isaac
I think there is a performance gain in list comps over explicit for
looping - I'm sure google will turn up some stats for this in this
newsgroup in the past.
As for list(<generator-expr>) over [<list-comprehnesion>], that's why
they make chocolate and vanilla. (I believe that at one time, Guido
was considering discarding list comps in Py3K, with this list
+generator expression alternative being the rationale for dropping
them, but later changed his mind.)
-- Paul
More information about the Python-list
mailing list