2

i'm having strange behavior from the for loop in python. The problem is not exactly this one but very similar to :

a = []
b = [1,2,3,4]
for i in xrange (0,10):
     a.append(b)
     b[3] += 1

And the result is :

a = [[1,2,3,14],[1,2,3,14],[1,2,3,14],[1,2,3,14],[1,2,3,14],[1,2,3,14],[1,2,3,14],[1,2,3,14],[1,2,3,14],[1,2,3,14]]

The result i'm expecting is

a =  [[1,2,3,4],[1,2,3,5],[1,2,3,6],[1,2,3,7],.....,[1,2,3,14]]

I do not know why at each iteration, b[3] is added up to 14 and then the list [1,2,3,14] is added to a. I think b[3] should only increase by 1 at each iteration

5
  • 2
    This is because you are appending a reference to b to a at each iteration of the loop, not a copy of b. Each reference points to the same b, which, at the end of your loop, has b[3] = 14. Commented Jun 20, 2012 at 11:16
  • 3
    Try pasting the code in this python code visualizer to see exactly what is happening. Commented Jun 20, 2012 at 11:18
  • @lazyr That is really helpful - glad I know about this now! Commented Jun 20, 2012 at 11:21
  • Thank a lot all of you guy :)) Commented Jun 20, 2012 at 11:28
  • @lazyr wow, there are even such things, but seems it is problematic, because even for simple code segments as such, it crashes. Commented Jun 20, 2012 at 12:21

3 Answers 3

7

Your problem is that every iteration you append a reference to the same array, and keep changing it.

The simplest fix is to change the append to

 a.append(list(b))

This will make every iteration append a (shallow) copy to the target array, instead of a reference.

Sign up to request clarification or add additional context in comments.

Comments

4

b is accessed by reference, so when you modify b[3] it's affecting every reference of it that you've appended to a over and over again. To fix this you just need to create a new copy of b each time:

a = []
b = [1,2,3,4]
for i in xrange (0,10):
     a.append(b[:])
     b[3] += 1

1 Comment

list(b) is much more novice friendly syntax for b[:]
2

you can use deepcopy:

from copy import deepcopy
a = []
b = [1,2,3,4]
for i in xrange (0,10):
     a.append(deepcopy(b))
     b[3] += 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.