Tutorial Study Image

Python count()

The count() function in python helps to return the number of occurrences of the given element in the tuple. A tuple is a built-in datatype that is used to store multiple elements it is ordered and unchangeable.


tuple.count(element) #where element may be a integer,string,etc.
 

count() Parameters:

The count() function takes a single parameter. If the parameter is missing it will return an error.

Parameter Description Required / Optional
element The element to be counted Required

count() Return Value

The return value is always an integer which indicates how many times the particular element is present in the tuple. If the given element is not present in the tuple it will return zero.

Input Return Value
element integer(count)

Examples of count() method in Python

Example 1: How Tuple count() work sin Pytho?


# vowels tuple
alphabets = ('a', 'b', 'c', 'd', 'a', 'b')

# count element 'a'
count = alphabets .count('a')

# print count
print('The count of a is:', count)

# count element 'c'
count = alphabets .count('c')

# print count
print('The count of c is:', count)
 

Output:


The count of a is: 2
The count of c is: 1

Example 2:How to count list and tuple elements inside Tuple?


# random tuple
random_tup = ('a', ('b', 'c'), ('b', 'c'), [1, 2])

# count element ('b', 'c')
count = random_tup.count(('b', 'c'))

# print count
print("The count of ('b', 'c') is:", count)

# count element [1, 2]
count = random_tup.count([1, 2])

# print count
print("The count of [1, 2] is:", count)
 

Output:


The count of ('b', 'c') is: 2
The count of [1, 2] is: 1