Python : Tuple
A tuple is an ordered, immutable collection of elements enclosed in parentheses
()and separated by commas. Once created, it cannot be modified, unlike lists that can be modified.
Creating a tuple is similar to creating a list in Python, but instead of enclosing the elements in square brackets, we use parentheses.
my_tuple = (1, 2, 3, 4)
Accessing Tuple Elements:
We can access individual tuple elements using indexing, just like lists. For example:
my_tuple = (1, 2, 3, 4) print(my_tuple) # Output: 1
Slicing can also be used to extract a range of elements from a tuple, just like with lists.
my_tuple = (1, 2, 3, 4) print(my_tuple[1:3]) # Output: (2, 3)
Although tuples are immutable, we can perform certain operations on them.
We can concatenate two tuples using the
"+" operator, which creates a new tuple with elements from both tuples.
my_tuple_1 = (1, 2, 3) my_tuple_2 = (4, 5, 6) my_tuple_3 = my_tuple_1 + my_tuple_2 print(my_tuple_3) # Output: (1, 2, 3, 4, 5, 6)
We can repeat a tuple using the
"*" operator, which creates a new tuple with elements repeated a specified number of times.
my_tuple = (1, 2, 3) print(my_tuple * 2) # Output: (1, 2, 3, 1, 2, 3)
Tuples have two methods:
count() method returns the number of times a specified element appears in the tuple.
my_tuple = (1, 2, 3, 2, 4, 5, 2) print(my_tuple.count(2)) # Output: 3
index() method returns the index of the first occurrence of a specified element in the tuple.
my_tuple = (1, 2, 3, 2, 4, 5, 2) print(my_tuple.index(2)) # Output: 1
Advantages of using Tuples:
Tuples are faster than lists as they are immutable, and their contents cannot be changed, which makes them more efficient.
Tuples can be used as dictionary keys, unlike lists, which cannot be used as keys.
Tuples can be used in situations where the order of the elements is important.