2

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

J. Murray
  • 1,460
  • 11
  • 19
echo Lee
  • 191
  • 1
  • 2
  • 10
  • `1,2,3` are constance not can change the value, but list its an object then when you assign `b` to `a` b you are creating a reference to b called `a` another words it same that a pointer to, then a is same b if you mutate one mute the reference "the memory" – juancarlos Oct 08 '19 at 22:44

3 Answers3

1
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.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

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).

chepner
  • 497,756
  • 71
  • 530
  • 681
-2

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

LtWorf
  • 7,286
  • 6
  • 31
  • 45