In order to find how many times an item or element occurs in a python list, count()
method is used.
count()
is a list method that takes an argument and returns the number of times the argument is present in the list or its count in the list.
count()
method accepts a single argument and returns its occurrences in the list. count()
returns 0 if the element is not present in the list.
count(element)
count() example
Below is an example of using count()
method on a list.
# define a list numbers = [2,4,4,1,9,5,4,99,3] # count the occurrences of 4 repeats = numbers.count(4) print('Count of 4 in list is:', repeats)
Above example creates a list with random numbers and then find the frequency or occurrence of 4 in the list using count()
method.
Here is the output.
Count of 4 in list is: 3
count()
can also be used to count the frequency of object in a list. This means that you can pass a string, tuple or a set as argument to count()
.Suppose there is a list of tuples and lists. With
count()
, you can also check the number of times a tuple or list exists in the list. Example,
numbers = [2,4,[4,1], (9,5),4,99,3] repeat_tuple = numbers.count((9, 5)) print('Count of tuple in list is:', repeat_tuple) repeat_list = numbers.count([4, 1]) print('Count of list in list is:', repeat_list)
Above code snippet creates a list with integers, tuple and list as elements and uses count()
method to find the number of times the tuple and list appear in the main list.
Below is the output
Count of tuple in list is: 1
Count of list in list is: 1
Do not forget to click the clap if the article was useful.