Tuples are immutable in Python | Why | Example

Python >   Python Tuples >   Python Tuples  

Long Question

326


Answer:

Tuples are immutable because once a tuple object is created, its contents cannot be modified. This means that you cannot add, remove, or change elements of a tuple.

This immutability is different from lists, which are mutable and allow you to modify their contents after creation. The immutability of tuples makes them useful in situations where you want to ensure that the contents of an object cannot be accidentally changed, such as when passing data between different parts of a program or when creating keys for dictionaries.

Because tuples are immutable, they are also more efficient than lists in terms of memory usage and performance, which makes them a good choice for situations where you need to store and access data quickly and efficiently.

Now Example

Sure, here's an example of why tuples are immutable:


# create a tuple
my_tuple = (1, 2, 3)

# try to modify the tuple
my_tuple[1] = 4

If you try to run this code, you'll get a TypeError with the message " tuple object does not support item assignment". This error occurs because tuples are immutable, and therefore you cannot modify the contents of a tuple once it has been created.

In contrast, if you were to create a list instead of a tuple, you could modify its contents:


# create a list
my_list = [1, 2, 3]

# modify the list
my_list[1] = 4

# check the contents of the list
print(my_list)  # outputs [1, 4, 3]

This code will run without error because lists are mutable, and therefore you can modify their contents.

This demonstrates the key difference between tuples and lists: tuples are immutable, while lists are mutable. Once you create a tuple, its contents cannot be modified, whereas lists can be modified after creation.


This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.