overview count() method
The List method count() returns the number of times a specified element appears in the given list.
count elements in a list
# count elements in a list
letters = ['a', 'a', 'h', 'g', 'b']
count = letters.count('a')
In this example, the list letters includes multiple letters and some of them multiple times.
The count() method is used to find how often the letter 'a' appears in the list. The result is then assigned to the variable count.
Finally, the count is printed and the result appears as shown below.
The element 'a' appears twice in the list and therefore the integer value 2 is returned.
syntax of count()
The syntax of the count() method is:
arguments of count()
The count() method takes a single argument, the element to be counted.
If no or more than one argument is given, a TypeError exception is raised.
TypeError: list.count() takes exactly one argument (0 given)
return value of count()
The count() method of lists in Python returns the number of times the specified element appears in the given list.
The return value is an integer and if the element is doesn't appear in the list the integer value 0 is returned.