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

1
  • 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" Commented Oct 8, 2019 at 22:44

3 Answers 3

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.

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

Comments

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

Comments

-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.