Python Tuple Methods

Tuples have only two built-in methods because tuples are immutable (cannot be changed after creation). count() The count() method returns the number of times a specified value appears in a tuple. Syntax Example Output: index() The index() method returns the position of the first occurrence of a specified value. Syntax Example Output: Using count() with […]

1 min read Lesson 35 of 40 88% through track

Tuples have only two built-in methods because tuples are immutable (cannot be changed after creation).

count()

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

Syntax

tuple_name.count(value)

Example

numbers = (10, 20, 30, 20, 40, 20)

print(numbers.count(20))

Output:

3

index()

The index() method returns the position of the first occurrence of a specified value.

Syntax

tuple_name.index(value)

Example

fruits = ("apple", "banana", "mango", "banana")

print(fruits.index("banana"))

Output:

1

Using count() with Strings

colors = ("red", "blue", "red", "green", "red")

print(colors.count("red"))

Output:

3

Using index() with Numbers

numbers = (100, 200, 300, 400)

print(numbers.index(300))

Output:

2

Error Example

If the value does not exist, index() raises an error.

fruits = ("apple", "banana", "mango")

print(fruits.index("orange"))

Output:

ValueError: tuple.index(x): x not in tuple

Check Before Using index()

fruits = ("apple", "banana", "mango")

if "orange" in fruits:
    print(fruits.index("orange"))
else:
    print("Item not found")

Output:

Item not found

Summary of Tuple Methods

MethodDescription
count()Returns the number of occurrences of a value
index()Returns the index of the first occurrence of a value

Key Points

  • Tuples are immutable, so they have very few methods.
  • count() is used to count repeated values.
  • index() is used to find the position of a value.
  • index() returns the first matching position only.
  • Using index() on a missing value raises a ValueError.