Python mutable and immutable objects @ Erwin | 2021-08-20T16:25:34+08:00 | 1 minute read | Update at 2023-12-06T00:27:08Z

Illuminating the difference between mutable and immutable objects in python

Mutable objects

The location of mutable objects will be changed when reassign value to it, it will not change when change the value.

Mutable objects contain list, dictionary, set and custom classes.

class person:
    def __init__(self,name):
        self.name = name

a = person("Li")
b = a
a.name, b.name
('Li', 'Li')
id(a), id(b)
(140342160258672, 140342160258672)
a.name = "Wang"
a.name, b.name
('Wang', 'Wang')
id(a), id(b)
(140342160258672, 140342160258672)
l1 = [1,2,3]
l2 = l1
l1, l2
([1, 2, 3], [1, 2, 3])
id(l1), id(l2)
(140342160434432, 140342160434432)
l2.append(2)
l1, l2
([1, 2, 3, 2], [1, 2, 3, 2])
id(l1), id(l2)
(140342160434432, 140342160434432)

immutable objects

The location of immutable objects will be changed when the value be changed, if location don’t be changed, the value can’t be changed too.

Immutable objects contain float, integer, tuple, string and frozenset.

© 2020 - 2024 Li Yuanhao's Blog

Powered by Hugo with theme Dream.

avatar

Li Yuanhao's BlogJust do it

Social Links