assignment in a for loop



Hello everyone

Consider the following

l = [1,2]
for i in l:
.... i = i + 1
....
l
[1, 2]

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

.



Relevant Pages

  • Re: how to iterate through each set
    ... It works only for first set. ... As you suggested you now need to loop over some of your code until you reach an end condition. ... Yes, Python will close it once the program has finished, but it's good practice to close it yourself as soon as you've finished with it. ... This won't be a problem in this assignment, but it may be in later assignments. ...
    (comp.lang.python)
  • Re: Assignment in a while?
    ... can't do an assignment in the while loop. ... (see the commented out while loop), ... In the beginning of my python experience, I was a bit irritated at ... irritation really doesn't last very long. ...
    (comp.lang.python)
  • Re: how to iterate through each set
    ... loop over some of your code until you reach an end condition. ... Now a few general pointers unrelated to your assignment: ... list is a keyword in python. ...
    (comp.lang.python)
  • Re: The LOOP macro
    ... comprehension, lets you code this common idiom concisely and directly. ... > that this loop which segregates elements of a list into three not ... In Python one would have to create lists first and give ...
    (comp.lang.lisp)
  • Re: Map with an extra parameter
    ... loop out of Python and into C, is that the case when using list ... a Python loop. ...
    (comp.lang.python)