The list
is the most flexible data type in Python, it represents an ordered collection of elements in which elements can appear more than once.
The count()
method is used to get the number of times that an element appears in a list.
The syntax of the count()
method is as shown below:
lst.count(item)
item |
The element whose count we want. |
The count()
method returns an integer representing the number of times the input item
appears in the list.
Count how many time each element appears in a list
If we want to check the count of each element in a list we can use list comprehension to conveniently count the elements.
In the above example, we used list comprehension to create a list of tuples in which each tuple is in the form (element, count)
for each unique element of the list.