Why do you think tuple is an immutable in Python?

In this article, we will discuss why tuples in python are immutable. Before moving on, we will understand tuples in detail.

Tuple

Tuples are a data type that belongs to the sequence data type category. They're similar to lists in Python, but they have the property of being immutable. We can't change the elements of a tuple, but we can execute a variety of actions on them such as count, index, type, etc.

Tuples are created in Python by placing a sequence of values separated by a 'comma', with or without the use of parenthesis for data grouping. Tuples can have any number of elements and any type of data (like strings, integers, lists, etc.).

Example 1

In the below example we will look at how to create a tuple.

tuple = ('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills')
print(tuple)


Output

The above code produces the following results

('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills')


Example 2

The following example depicts that tuples are immutable. Here we try to overwrite or replace “Levi” with the “Kristen” name, but as tuples are immutable we cannot use the index method to achieve it.

tuple = ("Meredith", "Levi", "Wright", "Franklin")
tuple[1]= "Kristen"
print(tuple)


Output

The above code produces the following results

File "main.py", line 2, in <module>
tuple[1]= "Kristen"
TypeError: 'tuple' object does not support item assignment


The following are a few important reasons for tuples being immutable.

• Maintaining Order − Tuples are mainly defined in python as a way to show order. For example, when you retrieve data from a database in form of a list of tuples, all the tuples are in the order of the fields you fetched.

• Copy efficiency − Rather than copying an immutable object, you can alias it (bind a variable to a reference).

• Comparing efficiency − You can compare two variables by comparing position rather than content when using copy-by-reference.

• Interning − Any immutable value requires just one copy to be stored. In concurrent programs, there's no requirement to synchronize access to immutable objects.

• Constant correctness − Some values shouldn't be allowed to change.