Python Tuple Methods Explained with Examples

Python Tuple has only two built-in methods.

count()

Python Tuple the count() method is used to count the number of occurrences of a specified element in a tuple.

Syntax

count = my_tuple.count(value)

Parameters

value: The element for which you want to count occurrences in the tuple.

Return Value

count: the number of times the specified element appears in the tuple.

Example

my_tuple = (1, 2, 2, 3, 4, 2, 5)
count = my_tuple.count(2)
print(count)  # Output: 3

index()

Python Tuple index() returns the index of the first occurrence of a specified element in a tuple.

Syntax

tuple.index(value, start, stop)

Parameters

value: The element whose index is to be found in the tuple.

start (optional): The index at which the search starts. Default is 0.

stop (optional): The index at which the search stops. Default is the end of the tuple.

Return Value

It returns the index of the first occurrence of the specified element in the tuple. If the element is not found, it raises a ValueError.

Exampe

my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.index(2))  # Output: 1

Important Notes

  • The index() method is case-sensitive when used with strings.
  • The index() method only returns the index of the first occurrence of the specified element, even if there are multiple occurrences.
  • The index() method has a time complexity of O(n), where n is the length of the sequence, because it needs to iterate over all elements to find the first occurrence.

Error handling

If the specified element is not found in the sequence, the index() method raises a ValueError. You can handle this error using a try-except block:

try:
    index = my_tuple.index(5)
except ValueError:
print("Element not found")