Python summary: mutable and immutable types


((Mutability and immutability))

In Python, the built-in types are objects. And obviously the objects are stored in memory. So, we can view the reference of an object by using the id() function:

>>> message = "Hello"
>>> id(message)
140604692041544

 

We created a Hello string. And the data types can be either mutable or immutable:

  • Immutable: integers, floats, strings, booleans, tuples, frozensets…
  • Mutable: lists, sets…

However, a exception exists: the type depends on dictionaries. For example, keys must be immutable. Read more about dictionaries in Python.

But what do inmmutable and mutable classification mean?

AccessibleModifiable
Immutable
Mutable

 

Some examples:

>>> num = 7 # IMMUTABLE TYPE
>>> id(num)
10455232
>>> num = 9 # We do not modify, but replace the reference ID assigned to the var
>>> id(num) # Obviously, we will obtain a different ID
10455296
>>> text = "Esperanto is the future" # IMMUTABLE TYPE
>>> id(text)
140604741450896
>>> text[0] # Accessing
'E'
>>> text[:9] = "English" # Again, we cannot modify because strings are immutable
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment
>>> text = "Esperanto is our open source language"
>>> id(text) # Obviously, we will obtain a different ID
140604742015968
>>> list = [1, 2, 3] # MUTABLE TYPE
>>> id(list)
140604692044616
>>> list[0]
1
>>> list[0] = 9 # We can do changes
>>> list
[9, 2, 3]
>>> id(list) # And the reference ID will keep being the same
140604692044616

 

Find out why the immutability/mutabilty difference exists, what the utility is, with an example:

[IMMUTABLE]            [MUTABLE]
>>> x = 1              >>> x = [1, 2, 3]
>>> y = x              >>> y = x
>>> y                  >>> y
1                      [1, 2, 3]
>>> x = 9              >>> x[0] = 9
>>> x                  >>> x
9                      [9, 2, 3]
>>> y                  >>> y
1                      [9, 2, 3]

[Different]            [Equal]
[!= object in memory]  [== object in memory]
[Change X != change Y] [Change X » change Y]
Imprimir

Sé el primero en comentar

    Deja un comentario