more pythonic
Alan Isaac
aisaac at american.edu
Fri Feb 29 18:57:05 EST 2008
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
More information about the Python-list
mailing list