Immutability is a fundamental concept in Python that dictates how a data type behaves once it’s been instantiated. An immutable object is an object whose state cannot be modified after it’s created. Including some of Python’s built-in types like int, float, bool, str, tuple, and frozenset.

Why Immutability?

Immutability has several benefits in programming:

  1. Simplifies code: Immutable objects are simpler to understand and reason about, as we don’t need to consider how they might be changed.

  2. Hashable: Since immutable objects can’t be changed, they are hashable. This allows them to be used as a dictionary key.

  3. Safe in a multi-threaded environment: Because immutable objects can’t be changed once created, they can be safely shared across multiple threads in multiprocessing or multithreaded environments without worrying about data corruption.

Let’s look at immutability with an example - the Python string:

1s = "Hello, Codebay"
2s[0] = 'h'

Running the code above will result in a TypeError because strings in Python are immutable, meaning that elements of a string cannot be changed once it has been assigned.

Now, let’s consider immutable data types in Python.

Immutable Python Data Types

  • Integers: In Python, integers are immutable. If you try to change the value associated with an integer, you’re actually creating a new object with a new value instead.

  • Strings: As previously illustrated, Python strings are also immutable. To ‘change’ a string, what actually happens is a new string is created and the variable is reassigned to this new string.

  • Tuples: Tuples are another example of an immutable Python data type. A tuple is essentially a list that can’t be modified post-declaration. So if you try to update a tuple, you will get an error.

Here is an example illustrating the immutability of above mentioned data types:

 1# Immutable data types
 2integer = 100
 5integer = 200
 8string = "Hello"
11string = "Hello, again"
14tuple_ = (1, 2, 3)
17tuple_ = (1, 2, 3, 4)

Each time we ‘change’ these variables, we’re actually creating entirely new objects.


Remember, in Python, reassigning a variable doesn’t edit the original object but instead points the variable to a new object.