Python List count()


Python List count() method

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

https://youtu.be/5FH9ISEXfxQ?si=UQdupvSP7OSovHet

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

Syntax of List count()

The syntax of List count() method is

list.count(value)

You can read the above expression as: in the list, 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 list, and count the occurrences of this value in the list.

Return value

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

Examples

1. Count the occurrences of 'apple' in the list

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

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

Python Program

my_list = ['apple', 'fig', 'apple', 'cherry']

count = my_list.count('apple')
print(f"Count : {count}")

Output

Count : 2

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

2. Count the occurrences of 'banana' in the list

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

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

Python Program

my_list = ['apple', 'fig', 'apple', 'cherry']

count = my_list.count('banana')
print(f"Count : {count}")

Output

Count : 0

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

Summary

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