Tuples are a type of data structure in Python that is mainly used to combine different types of values in a single parameter. It is also referred to as Heterogeneous behavior. For example, one employee's details can be stored in one tuple, such as ID, Name, Age, and Designation. Also, it supports a single data type list of values.
Code Example. Tuples.py
mixed_tuple = (1, "Eliz", 43,"Engineer")
print(mixed_tuple)
my_tuple = (1, 2, 3)
print(my_tuple)
print(my_tuple[1]) // To access element by index
To execute the code, open the new terminal and run a command called 'python Tuples.py'
Output
Tuples are immutable, which means they can’t be changed once it's created, like the example below.
Here, my_tuple is created with three items of integer values, and by using an index, when trying to change the 2nd item, we get an error saying the object does not support item assignment.
my_tuple = (1, 2, 3)
# Trying to change an element
try:
my_tuple[1] = 4 # This will raise an error
print(my_tuple)
except TypeError as e:
print(f\"Error: {e}\") # Output: Error: 'tuple' object does not support item assignment
Output