Contents
Download this page as:
Python library reference says:
Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects.
In short, it works as follows (simple assignment):
Things to note:
a single object can have several names bound to it:
In [1]: a = [1, 2, 3] In [2]: b = a In [3]: a Out[3]: [1, 2, 3] In [4]: b Out[4]: [1, 2, 3] In [5]: a is b Out[5]: True In [6]: b[1] = 'hi!' In [7]: a Out[7]: [1, 'hi!', 3]
By modifying b, we have also modified a! This is because a and b are just labels that point to the same object. If we want to make a copy, we can explicitly ask for one by using the list command:
In [8]: a = [1, 2, 3] In [9]: b = list(a) In [10]: a is b Out[10]: False In [11]: b[1] = 'hi!' In [12]: a Out[12]: [1, 2, 3]
Note that taking slices of lists does perform a copy:
In [13]: a = [1, 2, 3] In [14]: b = a[:2] In [15]: b Out[15]: [1, 2] In [16]: b[0] = 'hi!' In [17]: b Out[17]: ['hi!', 2] In [18]: a Out[18]: [1, 2, 3]
The key concept here is mutable vs. immutable
- mutable objects can be changed in place.
- immutable objects cannot be modified once created.
A very good and detailed explanation of the above issues can be found in David M. Beazley’s article Types and Objects in Python.