[Tutor] Accessing List items

Bill Mill bill.mill at gmail.com
Mon Mar 21 20:48:02 CET 2005


On Mon, 21 Mar 2005 11:57:21 +0000, Matt Williams
<matthew.williams at cancer.org.uk> wrote:
> Dear List,
> 
> Thanks for the help with the previous problem - now all solved!
> 
> I have a question about accessing lists. I'm trying to do something to
> each item in a list, and then assign it back into the list, overwriting
> the old value. However, the first loop here doesn't work, whereas the
> second loop does - but is very ugly.
> 
> x = "200%  inv_nodes=0-2  node_caps=no"
> y=x.split()
> 
> for i in y:
>     i="z"
> print y
> 
> for i in range(len(y)):
>     y[i]="z"
>     print y
> 
> Surely there must be a better way than this ?

As Max pointed out, listcomps are the best way to do it. Another way,
which is useful in more complicated scenarios:

for i, elt in enumerate(y):
    ...do something complex with elt...
    y[i] = elt

*** technical yapping about why your first loop doesn't work is below;
read it only if you're interested - don't get scared, you don't really
need to know it ***

The reason that the first list doesn't work is that a string is an
immutable object. Thus, when you change it, you basically just tell
python to rebind the local name "i" from one immutable object (a
string) to another immutable element (another string). This has no
effect on the list. If, however, "i" is a mutable object (such as a
list or a dict), then your loop works as expected:

>>> y = [[1]]
>>> for i in y: i.append(2)
...
>>> y
[[1, 2]]

In this case, modifying the list "i" works in-place by modifying the
actual mutable object. The change is reflected in the list "y",
because the actual object it encloses has changed.

I hope this makes sense, and maybe clears up a little of your
confusion about variables in Python. It is a bit confusing, even for
experienced pythonistas, so ask questions if you don't get it (and
you're interested). If not, you can get away without worrying about it
for the most part.

Peace
Bill Mill
bill.mill at gmail.com


More information about the Tutor mailing list