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!

2
  • Can you tell which version of python are you running.. ? Commented Sep 10, 2013 at 4:37
  • try b[:] = [1,1,1,1] Commented Sep 10, 2013 at 4:41

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.