Python Tuple Methods
In Python, tuples are immutable, meaning their contents cannot be changed after creation. As a result, they have only two built-in methods:
Method | Description |
count() | Returns the number of times a specified value appears in the tuple. |
index() | Returns the index of the first occurrence of a specified value in the tuple. |
Let’s see the code example of each method:
count()
method
my_tuple = (1, 5, 2, 3, 5, 6)
print(my_tuple.count(5)) # Output: 2
In the above example, the number 5
appears two times in my_tuple
, so count(5)
returns 2
.
index()
method
my_tuple = (5, 10, 15, 10, 25)
print(my_tuple.index(10)) # Output: 1
In the above example, the index(10)
returns the position of the first occurrence of the value 10
in the tuple. Since, 10
first appears at index 1
, that’s the output.