[Tutor] Re: References in loops

Brian Beck exogen at gmail.com
Sat Feb 12 14:07:05 CET 2005


Andrei wrote:
> Numbers are immutable, so the element 1 can't change into a 2 inside the 
> list. If 1 was not immutable, e.g. a list you could modify it and then 
> it would be "updated" in the original list too.

It doesn't have anything to do with mutability, only the scope of i. 
Consider a list of lists (lists are mutable):

py> l = [[1], [2], [3]]
py> for i in l:
         i = [0]

py> print l
[[1], [2], [3]]

Notice that even though each i (list) is mutable, rebinding the name i 
in the loop has no effect on the list.

> I tend to use list comprehensions for this:
> 
>     aList = [elem+1 for elem in aList]

This is probably the best solution, provided that the operation you want 
to perform on each element is simple enough to fit in an expression. 
Even then, just put the operation into a function.

--
Brian Beck
Adventurer



More information about the Tutor mailing list