Python Immutable Tuple
In Python, a tuple is a sequence type similar to a list. The primary difference between tuples and lists is that tuples are immutable; once created, their contents cannot be modified. This means that after creation, elements within a tuple cannot be added, removed, or modified.
A tuple can be created using a pair of parentheses, with elements separated by commas. For example, the following code shows an example of a tuple containing three elements:
my_tuple = (1, "hello", 3.14)
Each element within a tuple can be accessed via its index position within the tuple. For instance, to access the first element, you can use the following syntax:
my_tuple[0]
Tuples also support common sequence operations such as slicing, concatenation, and repetition. For example, to retrieve the first two elements of a tuple, you can use the following syntax:
my_tuple[:2]
You can also concatenate two tuples using the plus operator, for example:
my_tuple + (4, 5, 6)
It is important to note that if a tuple contains only one element, a comma must be added after the element. For example, the following code creates a tuple containing a single element:
# Create a singleton tuple with one element
my_singleton_tuple = (42,)
Tuples and lists are very similar in many aspects, but because tuples are immutable, they may be more suitable as containers for immutable data in certain scenarios. For example, tuples can be used as keys in dictionaries, whereas lists cannot.