[Tutor] List comprehension

Michael P. Reilly arcege@speakeasy.net
Wed, 23 Jan 2002 10:40:27 -0500


On Wed, Jan 23, 2002 at 12:48:08PM -0200, Marco A. Sousa wrote:
> Kirby Urner (urnerk@qwest.net) wrote:
> >   >>> [x*x for x in [1,2,3,4,5]]
> >   [1, 4, 9, 16, 25]
> 
> 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]
>>>

  -Arcege