Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 642
cuongptnk Avatar asked Dec 05 '25 19:12

cuongptnk


2 Answers

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.

like image 141
bdew Avatar answered Dec 08 '25 19:12

bdew


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
like image 20
mVChr Avatar answered Dec 08 '25 18:12

mVChr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!