Mutable & Immutable
Mutable
  • Changing the value of a mutable variable will not create a new object
  • list, byte array, sets, dict, class instances
    1. def changeMutable(v):
    2. v[2] = 100 # change 3rd element of v in main program
    3. v = [1, 2, 3, 4] # create a new object, not change v in main program
    4. l = list(range(10))
    5. changeMutable(l)
    6. print(l)# [0, 1, 100, 3, 4, 5, 6, 7, 8, 9]
    Immutable
  • Changing the value of an immutable variable will create a new object with a different id
  • int, float, complex, str, tuples, bytes, frozensets
    1. def changeNum(n):
    2. n *= 10 # create a new object, not change n in main program
    3. # python create 10 in memory, all three variable points to the same memory
    4. n = 10;
    5. n2 = n;
    6. n3 = 10;
    7. print(id(n), id(n2), id(n3))
    8. changeNum(n)
    9. print(n) # 10
    10. # create a string
    11. s = 'Hello '
    12. print(id(s)) # 4422154032
    13. # create a new string object
    14. s = s+'World!'
    15. print(id(s)) # 4422194416
    Assignment
    1. # create an object and assign the reference to l
    2. l = list(range(10))
    3. # assignment the reference of l to l2
    4. l2 = l
    5. # create a new object and assign the reference to l3
    6. l3 = list(range(10)) # mutable variable
    7. # l and l2 point to same object, l3 is a different object
    8. print(id(l), id(l2), id(l3))
    9. # create an immutable object
    10. i = (1, 2, 3, 4)
    11. # i and i2 point to same object
    12. i2 = i
    13. # create a new object
    14. i3 = (1, 2, 3, 4)
    15. print(id(i), id(i2), id(i3)) # i and i2 are same, and i3 have a different id
    User defined class
    1. class Vehicle(object):
    2. """Document String: Define a Vehicle class"""
    3. def __init__(self, brand):
    4. self._brand = brand;
    5. def __str__(self):
    6. return self._brand
    7.  
    8. def __hash__(self):
    9. return hash(self._brand)
    10.  
    11. def __eq__(self, other):
    12. if isinstance(other, self.__class__):
    13. return self._brand == other._brand
    14. return NotImplemented
    1. # mutable object
    2. def change(v):
    3. print('Inside function ...')
    4. print(id(v)) # 4350403216
    5. v._brand = 'Lincoln'
    6.  
    7. def main():
    8. v = Vehicle("Buick")
    9. print(id(v)) # 4350403216
    10. print(v) # Buick
    11.  
    12. change(v)
    13. print('After call change function ...')
    14. print(id(v)) # 4350403216
    15. print(v) # Lincoln
    16.  
    17. if __name__ == '__main__':
    18. main()
    1. # can be used as immutable object if __hash__ and __eq__ are defined
    2. # use as dictionary key
    3.  
    4. def main():
    5. v = Vehicle("Buick")
    6. container = {v: 100} # use Vehicle instance as key
    7.  
    8. print(container[Vehicle("Buick")])
    9.  
    10. if __name__ == '__main__':
    11. main()
    Resource
  • CODEHABITUDE