List Count Method in Python

From this tutorial, you will be learning about Python list Count method. You will see how to use it on sequences with the help of examples.

Note: The syntax used in the below section is for Python 3. You can change it to any other versions of Python.

Python List Count

To Learn about Lists – Read Python List

List Count Method

The Count Module is a built-in list method that allows you to count the occurrences of a particular element in the sequence.

Its syntax is as follows:

List_name.count(<element>)

This method counts the number of instances of an element in a list. See the below example.

>>> random_list = ["12", 12, (12, 13), 12, {12, 13}, 'linux', 'osx', 'win7']
>>> random_list.count(12)
2
>>> random_list.count("12")
1
>>>

You might have noticed that the output for string 12 was 2 and for the “12” was 1. It is because the list only counts the element which matches the data type and the value of the parameter passed.

If an element (For example – a number) gets enclosed in double quotes, then it gets treated as a string else as a numeric type. To understand this from depth, we recommend you to go over the tutorial on strings in Python.

How does the Count() function work?

This method takes a single argument as the input which represents the element whose occurrence to be determined.

It iterates the list and counts the number of instances that match and returns the total number of count.

Please note that the List count method returns 0 if it receives an invalid or non-existent parameter.

>>> random_list.count(-1)
0
>>> random_list.count(0)
0
>>> random_list.count(1000)
0

The flowchart below attempts to explain it in a diagram:

Python List Count Method Flowchart

Best,

TechBeamers