I am new to python and am trying to understand how it handles copies vs references in respect to list unpacking. I have a simple code snippet and am looking for an explanation as to why it is behaving the way it does.
arr = [1, 2, 3, 4]
[one, two, three, four] = arr
print(id(arr[0]), arr[0])
print(id(one), one)
one = 5
print(id(one), one)
The output is:
(16274840, 1)
(16274840, 1)
(16274744, 5)
I am not sure why one
is all the sudden moved to a different memory location when I try to modify its contents.
I am using python version 2.7.18.
This is my first post, so I apologize in advance if I am not adhering to the guidelines. Please let me know if I have violated them.
Thank you for all the responses. They have helped me boil down my misunderstanding to this code:
var = 1
print(id(var), var)
var = 5
print(id(var), var)
With output:
(38073752, 1)
(38073656, 5)
Asking about lists and unpacking them was completely obfuscatory.
This does a great job of explaining: http://web.stanford.edu/class/archive/cs/cs106a/cs106a.1212/handouts/mutation.html