1

Can someone please explain why this happens in Python?

>>> a = [1, 2, 3]
>>> b = a
>>> b[0] = 2
>>> print a
[2, 2, 3]
>>> a[0] = 4
>>> print b
[4, 2, 3]
>>> b = [111]
>>> print a
[4, 2, 3]

Basically, why can I reassign elements within a or b and change the other, but not change the other if I completely modify the list? Thank you!

user2717129
  • 661
  • 3
  • 7
  • 11

3 Answers3

6

When you assign b with a, both objects now point to the same memory location. So any changes done in either of the object will reflect in the other. The objects memory addresses become different when you assign 'b' with a new value. To elaborate:

>>> a=[1,2,3]
>>> b=a
>>> id(a)
4520124856
>>> id(b)
4520124856
>>> b=[111]
>>> id(a)
4520124856
>>> id(b)
4520173936 
>>> 

id() is used to obtain an object's memory address.

If you want to create a exact replica of 'a' without it having he same memory location, use b=a[:] which will create a copy of the data only.

Alagappan Ramu
  • 2,270
  • 7
  • 27
  • 37
0

That's because when you do b = [111] you are assigning a brand new list object to b. Therefore the b now contains the reference to the new list and no longer the reference to the older list.

Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208
0

as we define variable b = a python keep this value in memory location x. point a and b both x memory location. so we change in value of b value of a also changed. we assign new value to b so its store in another memory location and b points to new memory location. so value of a remains as it is.

Smita K
  • 94
  • 5