1

I have an integer array say offset=array('i',[0,0])

off=[]
offset=array('i',[0,0])
for each in [1,2,3]:
    offset[0]=j+each
    offset[1]=k+each
    print(offset)
    off.append(offset)
print(off)

I am appending the array in a list say off. My expected output is :

array('i', [2, 11])
array('i', [3, 12])
array('i', [4, 13])
[array('i', [2, 11]), array('i', [2, 12]), array('i', [4, 13])]

But, i am getting the output as:

array('i', [2, 11])
array('i', [3, 12])
array('i', [4, 13])
[array('i', [4, 13]), array('i', [4, 13]), array('i', [4, 13])]

Can anybody please help me in sorting it out ?

user3264821
  • 175
  • 2
  • 18
  • 5
    Read through this post about [shallow copy vs deep copy](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python) of lists. The reason I bring this up is because you are storing a copy of the same list in all your arrays, which is causing the problem you see. – Cory Kramer Jan 29 '15 at 12:44

1 Answers1

1

I think j = 1, and k = 10

and use your code like this:

from array import array

j,k = 1,10

off=[]
#offset=array('i',[0,0])
for each in [1,2,3]:
    offset=array('i',[0,0]) # move to here

    offset[0]=j+each
    offset[1]=k+each
    print(offset)
    off.append(offset)
print(off)

copy could help you, check How to clone or copy a list in Python? as Cyber advised you

from array import array
from copy import copy
j,k = 1,10

off=[]
offset_base=array('i',[0,0])
for each in [1,2,3]:
    offset=copy(offset_base)

    offset[0]=j+each
    offset[1]=k+each
    print(offset)
    off.append(offset)
print(off)
Community
  • 1
  • 1
Andres
  • 4,323
  • 7
  • 39
  • 53