Tuple methods in Python

In this exercise, we will learn about some tuple methods in Python.

1. count() method in Tuple The count() method returns the number of times a specified value appears in the tuple.

Example:

Python

# Tuple with repeated elements
numbers = (1, 2, 3, 2, 4, 2, 5)

# Count how many times 2 appears
count_of_two = numbers.count(2)

print("Tuple:", numbers)
print("Count of 2:", count_of_two)

Output Tuple: (1, 2, 3, 2, 4, 2, 5)
Count of 2: 3

2. index() method in Tuple The index() method returns the first index of the specified value. If the value is not found, it raises a ValueError.

Example:

Python

# Tuple with repeated elements
fruits = ("apple", "banana", "cherry", "banana", "apple")

# Find index of "banana"
first_banana_index = fruits.index("banana")

print("Tuple:", fruits)
print("Index of first 'banana':", first_banana_index)

Output Tuple: ('apple', 'banana', 'cherry', 'banana', 'apple')
Index of first 'banana': 1

Note: The index() method always returns the index of the first occurrence of the specified value.

3. min() in Tuple The min() function returns the smallest element in the tuple. It works for numbers, strings, or mixed comparable data types.

Example: with numbers

Python

# Tuple of numbers
numbers = (5, 2, 9, 1, 7)

# Find smallest number
minimum_value = min(numbers)

print("Tuple:", numbers)
print("Minimum value:", minimum_value)

Output Tuple: (5, 2, 9, 1, 7)
Minimum value: 1

Example: with strings

Python

# Tuple of strings
fruits = ("banana", "apple", "cherry")

# Alphabetically smallest string
minimum_fruit = min(fruits)

print("Tuple:", fruits)
print("Minimum (alphabetically):", minimum_fruit)

Output Tuple: ('banana', 'apple', 'cherry')
Minimum (alphabetically): apple

Note: String comparison is done using alphabetical (lexicographical) order.

4. max() in Tuple The max() function returns the largest element in the tuple.

Example: with numbers

Python

# Tuple of numbers
numbers = (5, 2, 9, 1, 7)

# Find largest number
maximum_value = max(numbers)

print("Tuple:", numbers)
print("Maximum value:", maximum_value)

Output Tuple: (5, 2, 9, 1, 7)
Maximum value: 9

Example: with strings

Python

# Tuple of strings
fruits = ("banana", "apple", "cherry")

# Alphabetically largest string
maximum_fruit = max(fruits)

print("Tuple:", fruits)
print("Maximum (alphabetically):", maximum_fruit)

Output Tuple: ('banana', 'apple', 'cherry')
Maximum (alphabetically): cherry

5. len() in Tuple The Python len() function returns the number of elements present in the tuple.

Syntax

len(tuple)

Example:

Python

# Create a tuple
my_tuple = ("Red", "Green", "Blue", 7)

# Length of tuple
print(len(my_tuple))

Output 4