cuongptnk
cuongptnk

Reputation: 472

how to modify this python for loop?

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

Upvotes: 2

Views: 118

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

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

Upvotes: 2

mVChr
mVChr

Reputation: 50185

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

Upvotes: 4

bdew
bdew

Reputation: 1330

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.

Upvotes: 7

Related Questions