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.
# 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.
# 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.