The count()
method in Python is used to count the number of occurrences of a specified element in a list. It returns the number of times the specified element appears in the list.
Parameter Values
Parameter | Description |
---|---|
element | The element to count in the list. |
Return Values
The count()
method from List in Python returns an int
.
How to Use count()
in Python
Example 1:
The count()
method returns the number of times a specified value appears in a list.
numbers = [1, 2, 3, 1, 4, 1, 5]
print(numbers.count(1)) # Output: 3
Example 2:
It can be used with any type of elements in the list, not just integers.
fruits = ['apple', 'banana', 'orange', 'apple']
print(fruits.count('apple')) # Output: 2
Example 3:
If the specified value is not in the list, it returns 0.
colors = ['red', 'blue', 'green']
print(colors.count('yellow')) # Output: 0