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.
>Solution :
The id/address is not associated with the variable/name; it’s associated with the data that the variable is referring to.
The 1 object is, in this instance, at address 16274840, and the 5 object is at address 16274744. one = 5 causes one to now refer to the 5 object which is at location 16274744.