Python Tuple count()

Python Tuple count() method

Python Tuple count() method counts the number of occurrences of specified value in the tuple, and returns that count.

In this tutorial, you will learn the syntax of Tuple count() method, and how to use this method in programs, with examples.

Syntax of Tuple count()

The syntax of Tuple count() method is

tuple.count(value)

You can read the above expression as: “In the tuple, count items that match the value.”

Parameters

count() method can take one parameter. Let us see the parameter, and its description.

ParameterDescription
valueThe value to be searched for, in the tuple, and count the occurrences of this value in the tuple.

Return value

count() method returns an int value, representing the number of occurrences of given value in the tuple.

Examples

1. Count the occurrences of value ‘apple’ in the tuple in Python

In the following program, we take a tuple my_tuple with some string values. We have to count the number of occurrences of the value 'apple' in this tuple.

Call count() method on the tuple my_tuple, and pass the value 'apple' as argument to the method.

Python Program

my_tuple = ('apple', 'fig', 'apple', 'cherry')

count = my_tuple.count('apple')
print(f"Count : {count}")
Run Code Copy

Output

Count : 2

Since there are two occurrences of the given value in the tuple, the count() method returned an integer value of 2.

2. Count the occurrences of ‘banana’ in the tuple in Python

In this example, we shall count the number of occurrences of the value 'banana' in the given tuple. We shall use the same tuple my_tuple from the previous example.

Since there are no items with the value 'banana', count should return 0.

Python Program

my_tuple = ('apple', 'fig', 'apple', 'cherry')

count = my_tuple.count('banana')
print(f"Count : {count}")
Run Code Copy

Output

Count : 0

Just as we mentioned, count() method returned 0.

Summary

In this tutorial of Python Examples, we learned about Tuple count() method, how to use count() method to count the number of occurrences of a specified value in the tuple, with syntax and examples.

Code copied to clipboard successfully 👍