Tuples are similar to lists in Python, representing an ordered collection of items. However, unlike lists, tuples are immutable, meaning their values cannot be changed once they are created. Despite their immutability, Python provides several methods for manipulating and working with tuples. In this article, we will discuss some of the most commonly used tuple methods in Python.
1) len(): This is built-in function which returns the number of items in a tuple.
For example:
a = (1, 2, 3, 4, 5) print(len(a)) # Output: 5
2) tuple.count(): This method returns the number of occurrences of a specified item in a tuple.
For example:
a = (1, 2, 3, 4, 5, 3, 3) print(a.count(3)) # Output: 3
3) tuple.index(): This method returns the index of the first occurrence of a specified item in a tuple.
For example:
a = (1, 2, 3, 4, 5) print(a.index(3)) # Output: 2
In conclusion, these are the only methods available for tuples in Python. Despite the limited set of methods, tuples can still be useful in many situations where we need to work with a collection of ordered, unchanging items. By understanding and using these methods, we can effectively work with tuples in Python.