Learn Python tuple methods with practical examples. Explore built-in tuple functions like count(), index(), and more for efficient Python programming.
Tuples are immutable sequences in Python, which means they have fewer methods than lists since they canβt be modified after creation. Here are the most important tuple methods and operations:
Definition: Returns the number of times a specified value appears in the tuple.
Syntax:
tuple.count(value)
Example:
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.count(2)) # Output: 3
Definition: Searches the tuple for a specified value and returns its position.
Syntax:
tuple.index(value, start, end)
Example:
my_tuple = ('a', 'b', 'c', 'b', 'a')
print(my_tuple.index('b')) # Output: 1
print(my_tuple.index('b', 2)) # Output: 3 (searches from position 2)
Definition: Returns the number of items in a tuple.
Syntax:
len(tuple)
Example:
my_tuple = (10, 20, 30)
print(len(my_tuple)) # Output: 3