The count() function in python helps to return the number of occurrences of a given element in the list.
list.count(element) #where element may be string, number, list, tuple, etc.
The count() function takes a single parameter. If more than one argument is passed to this method, it will return a TypeError.
Parameter | Description | Required / Optional |
---|---|---|
element | the element to be counted | Required |
The return value should be an integer showing the count of a given element. It returns a 0 if the given element is not found in the list.
Input | Return Value |
---|---|
any element | integer(count) |
# alphabets list
alphabets = ['a', 'b', 'c', 'd', 'e', 'c']
# count element 'c'
count = alphabets.count('c')
# print count
print('The count of c is:', count)
# count element 'f'
count = alphabets.count('f')
# print count
print('The count of f is:', count)
Output:
The count of c is: 2 The count of f is: 0
# random list
randomlist = ['a', ('a', 'b'), ('a', 'b'), [1, 2]]
# count element ('a', 'b')
countof = randomlist.count(('a', 'b'))
# print count
print("The count of ('a', 'b') is:", countof)
# count element [1, 2]
countof = randomlist.count([1, 2])
# print count
print("The count of [1, 2] is:", countof)
Output:
The count of ('a', 'b') is: 2 The count of [1, 2] is: 1