0

I think I found a strange problem regarding arrays. I initialize an array, array1, with no elements in it, and create another array, say array2, which I initialize to be exactly like array1. This is my code:

array1 = []
array2 = array1

Now, when I append an element to array1 and print out array2, this appears:

array1 = []
array2 = array1
array1.append(0)
print(array2)

>> [0]

Why exactly does array2 have that zero that I appended to array1? Why did it update its elements twice? It's like I wrote:

...
array2 = array1
array1.append(0)
array2 = array1
...

That's very strange in my opinion. Can anybody explain what happened here / what I did wrong?

petezurich
  • 9,280
  • 9
  • 43
  • 57
Acanum
  • 41
  • 2

1 Answers1

0

Basically you are referencing the same object in memory, after the assignment array2 = array1. You can check that these two references refer to the same object by using this code:

array1 = []
array2 = array1
array1.append(0)
array2 = array1 # Even if you didn't include this line, the check would still yield True.
print(array1 == array2) 

When run this outputs True: For more information regarding references and objects check this question How do I check if two variables reference the same object in Python?

solid.py
  • 2,782
  • 5
  • 23
  • 30
  • So basically it is an exact duplicate of that earlier question. – Jongware Mar 07 '20 at 19:08
  • @usr2564301 I use different code here, from both cited questions. – solid.py Mar 07 '20 at 19:09
  • @usr2564301 To further adjust it to op's question. – solid.py Mar 07 '20 at 19:11
  • 1
    Everyone's code will be different but the answer is still the same. See [Is it valid to vote to close as duplicate when the questions are at first glance unrelated?](https://meta.stackoverflow.com/questions/262853/is-it-valid-to-vote-to-close-as-duplicate-when-the-questions-are-at-first-glance/262858#262858) (and many more on [meta]) for a discussion. Do note that "being a duplicate" *in general* is not considered a problem (but in this case it is a straight duplicate IMO). – Jongware Mar 07 '20 at 19:23
  • @usr2564301 I was just trying to give him a better image, besides when I answered the question was still open. What do you think I should do? – solid.py Mar 07 '20 at 19:30
  • Thank you so much for your clear explanation. I'm sorry that this is a duplicate and I was unnecessarily wasting your time. I think I just searched badly. – Acanum Mar 09 '20 at 17:15
  • @Acanum No problem, don't worry, thanks for the accept ;) – solid.py Mar 09 '20 at 17:18