Lesson 7of 7
Python Tuple Methods - Complete Guide with Examples
Learn Python tuple methods with practical examples. Explore built-in tuple functions like count(), index(), and more for efficient Python programming.
Tuple Methods
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:
Common Tuple Methods
1. count()
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: 32. index()
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)3. len()
Definition: Returns the number of items in a tuple.
Syntax:
len(tuple)Example:
my_tuple = (10, 20, 30)
print(len(my_tuple)) # Output: 3