0

I just start to learn python, and today I stumble upon a behavior which I could not understand about python and its array, or maybe how python treat its variable, in this case arrays.

Here is the code that I have:

 some_array = [1,2,3,4,5,6]
 x = some_array
 x[2] = 10
 print(some_array)
 print(x)

Here is the output I got.

[1, 2, 10, 4, 5, 6]
[1, 2, 10, 4, 5, 6]

Here even though I changed only the third element of x, the initial some_array is also affected, which I really don't understand. It looks like to me, by using the instruction x = some_array, x and some_array then point to the same address space, therefore the behavior. Could someone please explain me this? And what should I do to avoid this situation?

Thanks a lot!

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
TLN
  • 11
  • 1

0 Answers0