Summary: In this tutorial, we will learn how to use the list.count() method to count the occurrence of elements in the Python list.
list.count(x) method of the list returns the count of the occurrence of the specified object/element in the list object.
For example here the
count() method counts the number of times the integer values 5 and 8 appear in the given list:
>>> l = [5, 8, 5, 9, 6, 9, 5] >>> l.count(5) 3 >>> l.count(8) 1
Also, if we look into the docstring of the
list.count we get that it returns the occurrences of the value (as discussed before):
>>> l.count.__doc__ 'Return number of occurrences of value.'
Parameters and Return Type
list.sort() accepts only one positional argument i.e. the object which needs to be counted and returns the count as the integer value.
Examples using list.count()
Example 1: Count the occurrence of a particular string in the list using
>>> l = ['sam', 'john', 'robert', 'sam', 'andrew'] >>> l.count('sam') 2
Example 2: Count the occurrence of a tuple in the given list
>>> l = [(1, 'Python'), (2, 'C++'), (3, 'Java'), (1, 'Python')] >>> l.count((1, 'Python')) 2 >>> l.count((1, 'Java')) 0
Example 3: Count frequency of a character in the string using the
>>> s = 'Pencil Programmer' >>> l = list(s) >>> l.count('m') 2
In this example, we are first converting the string into a list of characters using the
list() constructor and then using the
count() method on it to get the count of the particular character.
Example 4: Check if an element exists in the list using the
>>> l = [1, 2, 4, 5, 8] >>> if l.count(3) > 0: ... print('Item Exists') ... else: ... print('Item doesnt Exists') ... Item doesnt Exists
list.count(x) returns the number of times the element
x appears in the list.
We can use this method to get the count of an element or to check whether a particular element exists in the given list.