Search code examples
pythonvariables

Why variable assignment behaves differently in Python?


I am new to Python and I am quite confused about the following code:

Example 1:

n = 1
m = n
n = 2
print(n)   # 2
print(m)   # 1

Example 2:

names = ["a", "b", "c"]
visitor = names
names.pop()
print(names)      # ['a', 'b']
print(visitor)    # ['a', 'b']

Example 1 shows that n is 1 and m is 1. However, example 2 shows that names is ['a', 'b'], and visitor is also ['a', 'b'].

To me, example 1 and example 2 are similar, so I wonder why the results are so different? Thank you.


Solution

  • Integers are not mutable. So the only way to change a variable that is assigned to an integer is through assignment. When you assign m=n, m is assigned to the same address that n currently is assigned. Both m and n refer to the address of the integer 1. m will continue to point to 1 even if n is assigned to a different value be it an integer or something else entirely.

    This behavior based on assignment is common to both mutable and immutable types.

    By contrast, lists are mutable so you can modify by means that are not only assignment. When you assign visitor = names, visitor points to the same list that names is assigned to, just like the above case. And were you to change the value of names through assignment visitor would not be impacted. The difference emerges if you mutate the list. If you call names.pop() for example this mutates the list and visitor (and any other variable that was assigned to this list) will see the mutation. In your case you mutated the list with a pop operation, there are others which we won't go into here.