Python List count() method
The count() method is used to find the number of times a specific element occurs in a list. It is very useful in scenarios where we need to perform frequency analysis on the data.
Let’s look at a basic example of the count() method.
a = [1, 2, 3, 1, 2, 1, 4]
# count given number in list
c = a.count(1)
print(c)
Output
3
Explanation: a.count(1) counts the occurrences of 1 in the list as it is occurring 3 times in the list so the output is 3.
Table of Content
Syntax of count() Method
list_name.count(value)
- list_name: The list object where we want to count an element.
- value: The element whose occurrences need to be counted.
The count() method returns an integer value, which represents the number of times the specified element appears in the list.
Example of count() method
The count() method also works well with list that have different types of data.
a = [1, 'GfG', 3.14, 'GfG', 1, True]
c1 = a.count('GfG')
c2 = a.count(1)
print(c1)
print(c2)
Output
2 3
Explanation: The list a contains both strings and numbers. The string ‘GfG‘ appears twice and number 1 appears twice as well. But notice that output for 1 is 3 because Python counts True as 1 because True is equivalent to 1 in numerical operations.
Count occurrence of sub-list in list of Lists
The count() method does not search within nested lists and it will only count occurrences at the top level.
a = [1, [2, 3], 1, [2, 3], 1]
c = a.count([2, 3])
print(c)
Output
2
Explanation: Here, [2, 3] is treated as a single element in the list. The count() method counts it twice because it appears twice as a nested list.
Also Read:
- Count occurrences of an element in a list
- How to Get the Number of Elements in a Python List?
- Find all elements count in list
- Find most frequent element in a list