Python - Tuple Methods
Explore Python's built-in methods for tuples. Learn how to use these methods to manipulate and interact with tuples effectively in your Python programs.
Python - Tuple Methods
Python has two built-in methods that you can use with tuples:
Method | Description |
---|---|
count() |
Returns the number of times a specified value occurs in a tuple. |
index() |
Searches the tuple for a specified value and returns the position where it was found. |
Example: Using count()
Here is an example of how to use the count()
method:
Example
mytuple = ("apple", "banana", "cherry", "apple", "cherry", "cherry")
count_apple = mytuple.count("apple")
count_cherry = mytuple.count("cherry")
print(count_apple)
print(count_cherry)
Output
2
3
Example: Using index()
Here is an example of how to use the index()
method:
Example
mytuple = ("apple", "banana", "cherry", "apple", "cherry", "cherry")
index_banana = mytuple.index("banana")
index_cherry = mytuple.index("cherry")
print(index_banana)
print(index_cherry)
Output
1
2