0

I'm having trouble understanding how python pointers/ references work.

Take for example,

my_list = [1,2,3,4]
A = [my_list]*3
print("Before the change", A)
my_list[2]=45
print("After the change ", A)

The code will print "After the change [[1, 2, 45, 4], [1, 2, 45, 4], [1, 2, 45, 4]]"

However, if I do my_list = [10,20,30,40], A will not change even though, as I understand it, A points to the reference of my_list. What is actually happening? Is A pointing to the object [1,2,3,4] or to the variable my_list?

Note: I use pointer and reference to mean the same thing(Please tell me if it doesn't...)

BigBear
  • 188
  • 10
  • `my_list` is *not copied*, you have 3 references to a single list. – Martijn Pieters Jul 12 '19 at 19:10
  • `A[0]`, `A[1]`, `A[2]` and `my_list` are all references, and they all point to a single object, the list initially assigned to `my_list`. Assigning a different object to `my_list` won't change what `A[0]`, `A[1]` and `A[2]` point to. – Martijn Pieters Jul 12 '19 at 19:11
  • But when I did ```my_list[2]=45```, did I change the object or just the pointer since A[0], A[1], and A[2] changed. – BigBear Jul 12 '19 at 19:24
  • You changed the reference at `my_list[2]`, so one of the indices in the list object referenced by `my_list`. Since `A[0]`, `A[1]` and `A[2]` all reference that same list object, everything you did to the list via one reference is visible via the other references. – Martijn Pieters Jul 12 '19 at 21:20
  • You really want to read https://nedbatchelder.com/text/names.html here. – Martijn Pieters Jul 12 '19 at 21:20

0 Answers0