assignment in a for loop
- From: "MackS" <mackstevenson@xxxxxxxxxxx>
- Date: 16 May 2006 21:36:30 -0700
Hello everyone
Consider the following
.... i = i + 1l = [1,2]
for i in l:
....
[1, 2]l
I understand (I think!) that this is due to the fact that in Python
what looks like "assignment" really is binding a name to an object. The
result is that inside the loop I am creating an object with value (i+1)
and then "pointing" the name i at it. Therefore, the object to which i
previously pointed (an element of list l) remains unchanged.
Two brief questions:
1) Is what I wrote above (minimally) correct?
2) Independently of the answer to 1, is there a way for me to assign to
elements of a list inside a loop and without resorting to C-style
ugliness of
for i in range(len(l))
l[i] = l[i] + 1
?
(Note: not using a list comprehension.)
Thanks in advance
Mack
.
- Follow-Ups:
- Re: assignment in a for loop
- From: Ben Finney
- Re: assignment in a for loop
- From: MackS
- Re: assignment in a for loop
- Prev by Date: Re: build now requires Python exist before the build starts
- Next by Date: Re: Creating an Active Desktop Window
- Previous by thread: A better way of making subsclassing of built-in types stick for attributes?
- Next by thread: Re: assignment in a for loop
- Index(es):
Relevant Pages
|