[Tutor] List comprehension

Marco A. Sousa marcolinux@linuxbr.com.br
Wed, 23 Jan 2002 12:48:08 -0200


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?
Thanks in advance and thanks for all that answered my previous question
on removing itens from a list.

-- 
Buy a copy of a baby naming book and you'll never be at a loss for 
variable names.
- How To Write Unmaintainable Code