Speaking of list-comprehension?

Terry Hancock hancock at anansispaceworks.com
Fri Jul 1 01:17:54 EDT 2005


On Thursday 30 June 2005 10:13 pm, Chinook wrote:
>  >>> ta = [5, 15, 12, 10, 9]
>  >>> for i in range(len(ta)):
> ...   if ta[i] >= 10:
> ...     ta[i] -= 10
> ...   else:
> ...     ta[i] += 10

It's not exactly the same in that it doesn't change values in
place, but this is similar if you are only interested in the
values:

ta = [t>=10 and t-10 or t+10 for t in ta]

(this rebinds ta, so if you had a former reference to ta, it
won't be changed by this code).

In general, I don't think in-place operations are in the
domain of list comprehensions, since they are expressions.
I might be able to mangle something into doing it, but it's
probably a bad idea anyway. I think your loop is stylistically
fine as is (if you need to change the list in place).

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list