Robotics & Artificial Intelligence
Write a Python program to demonstrate difference between list and tuple.
Getting Started
2 Likes
Answer
# Declaring a list
my_list = [5, 8, 9, 12, 45]
print(my_list[1])
# Modifying an element of the list
my_list[1] = 56
print(my_list)
# Declaring a tuple
my_tuple = (5, 8, 9, 12, 45)
print(my_tuple[1])
# Trying to modify an element of the tuple
my_tuple[1] = 56
In the above program, a list is created using square brackets [ ] and it is a mutable data type, so its elements can be changed after creation. Therefore, modifying the value at index 1 in the list is possible. A tuple is created using parentheses ( ) and it is an immutable data type, so its elements cannot be changed after creation. Attempting to change a tuple element results in a TypeError, which shows the difference between a list and a tuple.
Answered By
2 Likes