Skip to content Skip to sidebar Skip to footer

Python Referenced For Loop

I'm playing with for loops in Python and trying to get used to the way they handle variables. Take the following piece for code: a=[1,2,3,4,5] b=a b[0]=6 After doing this, the zer

Solution 1:

Everything in python is treated like a reference. What happens when you do b[0] = 6 is that you assign the 6 to an appropriate place defined by LHS of that expression.

In the second example, you assign the references from the array to i, so that i is 1, then 2, then 3, ... but i never is an element of the array. So when you assign 6 to it, you just change the thing i represents.

http://docs.python.org/reference/datamodel.html is an interesting read if you want to know more about the details.

Solution 2:

That isn't how it works. The for loop is iterating through the values of a. The variable i actually has no sense of what is in a itself. Basically, what is happening:

# this is basically what the loop is doing:# beginning of loop:i = a[0]
i = 6# next iteration of for loop:i = a[1]
i = 6# next iteration of for loop:i = a[2]
i = 6# you get the idea.

At no point does the value at the index change, the only thing to change is the value of i.

You're trying to do this:

for i in xrange(len(a)):
    a[i] =6# assign the value at index i

Solution 3:

Just as you said, "The = sign points a reference". So your loop just reassigns the 'i' reference to 5 different numbers, each one in turn.

Post a Comment for "Python Referenced For Loop"