Python Tuples : In this Unit…
Python Tuple Methods| count() and index() in Python Tuples
Pre-requisite : All about Python Tuples
count() method in Python Tuple
count() method in Python Tuple can be used to count the number of occurrences of a given element in a tuple.
The count() method returns an integer value denoting how many times a particular element is found in a tuple.
Syntax
tuple.count(item)
tup = (10, 13, 12, 14, 15, 20, 15)
print(tup.count(15))
O/P
2
Counting an inner tuple inside main tuple
tup = (10, 15, (10, 20), 40, (10, 20), (10, 20, 30), (10, 20))
print(tup.count((10, 20)))
O/P
3
index() method in Python Tuple
index() method in Python Tuple can be used to find the first occurrence of a given element in the given tuple.
The index() method by default, returns an integer, denoting the first occurrence of the given element in that tuple.
Please note that, integer is returned as per 0 based indexing.
Syntax
tuple.index(item)
item: element whose index is required.
l = (1, 3, 5, 2, 8, 3)
print(l.index(2)) # returns 3
print(l.index(8)) # returns 4
print(l.index(3)) # returns 1 ignoring the further occurrences
O/P
3
4
1
If we try to find the index of the element which does not exists in the given tuple, then, we get
ValueError : item is not in tuple
Let’s modify the above code (a bit)
l = (1, 3, 5, 2, 8, 3)
print(l.index(10))
O/P
Traceback (most recent call last):
File “”, line 2, in
ValueError: 10 is not in tuple
That’s all here.
