0

How to copy array correctly? 2 methods give different outputs. I can't understand the logic behind it. What I wanted to achieve was the first one. Remove the repeating ones once the event occurs think it as time series. How is assigning predefined array differs from initializing new one?

myarray = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
         
duparray = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]

for i in range(0, len(myarray)):
    if myarray[i] == myarray[i-1] and myarray[i] == 1:
        duparray[i] = 0
        
print(duparray)

OUTPUT: [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
myarray = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
         
duparray = myarray

for i in range(0, len(myarray)):
    if myarray[i] == myarray[i-1] and myarray[i] == 1:
        duparray[i] = 0
        
print(duparray)

OUTPUT: [0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]
aekiratli
  • 518
  • 7
  • 18
  • 1
    `duparray = myarray` isn't creating a copy. It's just a new reference to the same object. – Wups Apr 01 '22 at 14:08
  • SIdenote: Everyone referring to arrays here actually refers to lists as Python uses lists by default. – Banana Apr 01 '22 at 14:14

1 Answers1

1

When you assign an array to a new variable, all the changes made on the previous one is transferred to the new one.

One way of doing this is by making a copy of the array.

myarray = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
         
duparray = myarray.copy()

This way, any changes on 'myarray' won't pass to 'duparray'.