Common Tuple Methods
Tuples have limited methods compared to lists because they are immutable. The two built-in methods are count()
and index()
.
count()
Method
Example: Counting Occurrences
# Using count()
tuple_data = (1, 2, 3, 2, 4, 2)
count_of_twos = tuple_data.count(2)
print("Count of 2s:", count_of_twos)
Output
Count of 2s: 3
index()
Method
Example: Finding the Index of an Element
# Using index()
tuple_data = ("Apple", "Banana", "Cherry", "Banana")
index_of_banana = tuple_data.index("Banana")
print("First Index of 'Banana':", index_of_banana)
Output
First Index of 'Banana': 1
Using len()
Function
Example: Getting the Length of a Tuple
# Using len()
tuple_data = ("Karthick AG", "Durai", "Vijay", "John")
tuple_length = len(tuple_data)
print("Tuple Length:", tuple_length)
Output
Tuple Length: 4
Explanation: The len()
function returns the number of items in a tuple.