Python List vs Python Tuple

Test whether tuples are immutable and lists are mutable

Here we are going to compare the list and tuple mutability tests.

Python3
# Creating a List with
# the use of Numbers
# code to test that tuples are mutable
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("Original list ", List)

List[3] = 77
print("Example to show mutability ", List)

Output
Original list  [1, 2, 4, 4, 3, 3, 3, 6, 5]
Example to show mutability  [1, 2, 4, 77, 3, 3, 3, 6, 5]

We can see here tuple can not be modified.

Python3
# code to test that tuples are immutable

tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)

Output:

Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment

Difference Between List and Tuple in Python

Lists and Tuples in Python are two classes of Python Data Structures. The list structure is dynamic, and readily changed whereas the tuple structure is static and cannot be changed. This means that the tuple is generally faster than the list. Lists are denoted by square brackets and tuples are denoted with parenthesis.

Similar Reads

Differences between List and Tuple in Python

Sno LIST TUPLE 1Lists are mutableTuples are immutable2The implication of iterations is Time-consumingThe implication of iterations is comparatively Faster3The list is better for performing operations, such as insertion and deletion.A Tuple data type is appropriate for accessing the elements4Lists consume more memoryTuple consumes less memory as compared to the list5Lists have several built-in methodsTuple does not have many built-in methods.6Unexpected changes and errors are more likely to occurBecause tuples don’t change they are far less error-prone....

Python List vs Python Tuple

Test whether tuples are immutable and lists are mutable...

Which is better list or tuple in Python?

To put this answer to the test, let’s run some operations on a Python Tuple and a Python List. This will give us a better idea of which is a better list or tuple in Python....

Mutable List vs. Immutable Tuples

In Python, both lists and tuples support a range of operations, including indexing, slicing, concatenation, and more. However, there are some differences between the operations that are available for lists and tuples due to their mutability and immutability, respectively....

When to Use Tuples Over Lists?

In Python, tuples and lists are both used to store collections of data, but they have some important differences. Here are some situations where you might want to use tuples instead of lists –...