From this tutorial, you will learn about the Python list Count method. You will see how to use it on sequences with the help of examples.
Introduction to Python List Count()
The count() is a built-in Python list method that allows you to calculate the occurrences of a particular element in the sequence.
Note: The syntax used in the below section is for Python 3. You can change it to any other version of Python.
List Count()
If you want to know the size of a list you are using in your Python program, this is the method you should call.
The following is the syntax to use this method in your Python programs.
Syntax
Its syntax is as follows:
List_name.count(<element>)
Example
See the below examples.
random_list = ["12", 12, (12, 13), 12, {12, 13}, 'linux', 'osx', 'win7']
print(random_list.count(12))
## 2
print(random_list.count("12"))
## 1
You might have noticed that the output for string 12 was 2 and for the “12” was 1. This is because Python only counts the element that matches the data type and the value of the parameter passed.
If an element (For example – a number) gets enclosed in double quotes, it gets treated as a string else as a numeric type. To understand this in-depth, we recommend you go over the tutorial on strings in Python.
How does list Count() work?
This method takes a single argument as the input representing the element whose occurrence is to be determined.
It iterates the list, records the number of instances that match and returns the total number of counts.
Please note that the List count method returns 0 if it receives an invalid or non-existent parameter.
print(random_list.count(-1))
## 0
print(random_list.count(0))
## 0
print(random_list.count(1000))
## 0
The flowchart below attempts to explain it in a diagram:
Before you leave
Hopefully, you have now full understanding of using the list count() method. If you any programming quer, we’ll be happy to address it.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Facebook) if you gained some knowledge from this tutorial.
Enjoy coding,
TechBeamers.