Re: assignment in a for loop



"MackS" <mackstevenson@xxxxxxxxxxx> writes:

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.

That's a fair explanation, yes.

Two brief questions:

1) Is what I wrote above (minimally) correct?

Correct for what? You can tell if it's *syntactically* correct by
simply running it.

As for any other "correct", define that. Does it do what you want it
to do?

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

You can build a new list from your operations on the old one.

new_list = []
for x in old_list:
new_list.append(x+1)

You can also do it more succinctly with a list comprehension
expression.

(Note: not using a list comprehension.)

What's preventing the use of list comprehensions?

new_list = [x+1 for x in old_list]

--
\ "Smoking cures weight problems. Eventually." -- Steven Wright |
`\ |
_o__) |
Ben Finney

.



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: DataTable Processing
    ... talking about binding, XML, or other things above and beyond what I ... > Use the DataTable.Select method to return an array of DataRows. ... > can loop through the array. ...
    (microsoft.public.dotnet.languages.vb)
  • RE: datetime.iterdate
    ... > List comprehension to the rescue: ... > loop where you do something (rather in a function ... Listcomps just shuffle syntax; I'm trying ...
    (comp.lang.python)
  • Re: The Lisp CPU
    ... If profiling shows there's a tight loop ... Because you're using dynamic binding, ... and re-bind them all with the most-crucial ...
    (comp.lang.lisp)
  • Re: Need help with C Language
    ... What exactly is array mmm being assigned to if the maskdatset is not ... could someone explain what exactly is happ in the switch case ... I mean is it necessary to put if(mmmloop before assignment ...
    (comp.lang.c)