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 ?

1
  • 5
    Read through this post about shallow copy vs deep copy 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. Commented Jan 29, 2015 at 12:44

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

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.