Tuple Methods and Built-in Functions
Due to their immutable nature, tuples have a very small set of native methods. However, they work perfectly with a wide range of Python’s built-in functions. This guide covers both.
1. Native Tuple Methods
Tuples have only two methods: count()
and index()
. Both are used for inspecting the tuple’s contents without modifying it.
tuple.count(value)
This method returns the number of times a specified value
appears in the tuple.
Pyground
Count the number of 'A' grades in a tuple of student scores.
Expected Output:
The grade 'A' appears 3 times.
Output:
2. Built-in Functions for Tuples
Many of Python’s built-in functions are designed to work with any iterable, including tuples.
Because tuples are immutable, these functions never modify the original tuple. They always return a new value, list, or iterator.
len()
Returns the number of items in the tuple. This is a constant-time operation.
Pyground
Find the length of a tuple.
Expected Output:
The tuple has 3 elements.