-3

In python, a=b=1 assigns 1 to the two variables at the same memory location. Then why does changing the value of one variable(variable a) does not affect the value of other(variable b)?

  • 4
    How do you know that "`the two variables at the same memory location`"? I want you to give me an answer to this question since lots of programmers have this notion and I don't know where they get it from. – quamrana Feb 13 '18 at 15:10
  • @quamrana I believe he did `a = b = 1`, and then `id(a), id(b)`, which yields the same results. – IMCoins Feb 13 '18 at 15:15
  • If you do `a=b` then you have pointed `a` towards the same data `b` holds. If you do `a=5`, you have pointed it to something else. Why should that affect `b`? – khelwood Feb 13 '18 at 15:16
  • 1
    Please see [Other languages have "variables", Python has "names"](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables). – PM 2Ring Feb 13 '18 at 15:22
  • @quamrana I got it from here. "variables are assigned to the same memory location" has been clearly mentioned. https://www.tutorialspoint.com/python/python_variable_types.htm – Raj Shrivastava Feb 13 '18 at 15:24
  • @RajShrivastava: Ok, I see. Its misleading because it implies the variables themselves share the same memory location. In python the names of the variables (`a` and `b` in your example) are stored somewhere (as strings) along with some sort of pointer which does the referencing. So, given that the `1` occupies a memory location, then both of the pointers that `a` and `b` own point to this. A subsequent `a = 2` just makes `a` point somewhere else. – quamrana Feb 13 '18 at 15:32

2 Answers2

4

Python does not deal in terms of memory locations. a = b = 1 assigns two new names, a and b, both pointing at the integer 1. Changing what one of the names points at does not affect what the other points at.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

In Python, there is a difference between assignment and mutation:

a = b = 1
print(a, b)
a = 2                # Here is a re-assignment
print(a, b)
a = b = []
print(a, b)
a.append(1)          # Here is a mutation
print(a, b)

Output:

1 1
2 1         # a has been reassigned
[] []
[1] [1]     # the list they point to has mutated
quamrana
  • 37,849
  • 12
  • 53
  • 71