# # .. contents:: # # Download this page as: # # - :download:`a commented Python script ` # - :download:`a minimal Python script ` # # Assignment operator # =================== # # `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): # # #. an expression on the right hand side is evaluated, the corresponding # object is created/obtained # #. a **name** on the left hand side is assigned, or bound, to the # r.h.s. object # # Things to note: # # * a single object can have several names bound to it: # a = [1, 2, 3] b = a a b a is b # # In [1]: b[1] = 'hi!' # # In [1]: a # # * 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: # a = [1, 2, 3] # # In [1]: b = list(a) # # In [1]: a is b # # In [1]: b[1] = 'hi!' # # In [1]: a # # * Note that taking slices of lists does perform a copy: # a = [1, 2, 3] b = a[:2] b b[0] = 'hi!' b a # * 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 # `_.