[Tutor] List comprehension

Jeff Shannon jeff@ccvcorp.com
Wed, 23 Jan 2002 10:05:14 -0800


>  "Michael P. Reilly" <arcege@speakeasy.net> wrote:
>
> > Based on this example I started to play with list comprehension and make
> > a "filter":
> > >>> [x*x for x in [1,2,3,4,5] if x*x <= 15]
> > [1, 4, 9]
> >
> > Then I changed the equation:
> > >>> [2*x*x for x in [1,2,3,4,5] if 2*x*x <= 15]
> > [2, 8]
> >
> > It works, but is hard to change the equation in two places. Furtermore I
> > think it's inefficient since the equation is evaluated twice. Or not ?
> > How can I make it more elegant?
>
> Using solely list comprehensions, how about:
>
> >>> [x for x in [2*x*x for x in range(1, 6)] if x <= 15]
> [2, 8]
> >>>

List comprehensions do some less-than-obvious things with local variables, though, so
just on principle I'd recommend against re-using the variable name.  It might not make
a difference in this case, but it might in some other... plus, I think it's a little
more readable anyhow--makes it a little more clear which list-comp the various
subexpressions apply to.

[x for x in [2*y*y for y in range(1,6)] if x <= 15]


Jeff Shannon
Technician/Programmer
Credit International