Reference Assignment in Python - Why isn't the value changed?

Viewed 162

I know that "variable assignment" in python is, in fact, a binding / re-binding of a name (the variable) to an object.

b = [1,2,3]
a = b[2] # binding a to b[2] ?
a = 1000

b is [1, 2, 3]

after this change, why b is not changed?

here is another example:

b = [1,2,3]
a = b
a[0] = 1000

this case b is [1000, 2, 3]

isn't assignment in Python reference binding?

Thank you

3 Answers
a = b[2] # binding a to b[2] ?

Specifically, this binds the name a to the same value referenced by b[2]. It does not bind a to the element in the list b at index 2. The name a is entirely independent of the list where it got its value from.

a = 1000

Now you bind the name a to a new value, the integer 1000. Since a has no association with b, b does not change.

In your second example:

a = b

Now a is bound to the same list value that b is bound to. So when you do

a[0] = 1000

You modify an element in the underlying list that has two different names. When you access the list by either name, you will see the same value.

a[0] = ... is a special form of assignment that desugars to a method call,

a.__setattr__(0, ...)

You aren't reassigning to the name a; you are assigning to a "slot" in the object referenced by a (and b).

Lists are mutable objects, ints aren't. 4 can't become 5 in python, but a list can change its contents.

Related