Python count occurrences of all items in list
In this post, you will learn how to count the occurrences of all items in a list using the Python programming language.
A list is an arranged collection of elements. It is used to store collections of data. It can contain a list of various types of data objects with a comma separated and enclosed within a square bracket. It is mutable, which means we can change the order of elements. Individual elements can be replaced even after the list has been created. This is one of the leading reasons why lists are being widely used. Lists play an effective role in small projects as they consume more memory.
list1 = ["Hii", 16, "Welcome", 10, 4]
Python count occurrences of all items in list using count() method
The count() method of Python returns the count of how many times a given object occurs in a given list.
Syntax-list_name.count(object)
Here, object is the item whose count is to be returned. This method returns the count of how many times an object occurs in the list.
a_list = ['cow', 'cow', 'ox', 'ox', 'ox', 'goat', 'cow', 'dog']
print(a_list.count('cow'))
print(a_list.count('ox'))
print(a_list.count('goat'))
Output of the above code:
3
3
1
Python count occurrences of given item in list using for loop
In the given Python program, we have used for loop to count how many times a given object occurs in a list.
# Python code to count the number of occurrences
def count_item(lst, x):
count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
# Driver Code
lst = ['a','a','b','c','d','c','e','d','e','e']
x = 'e'
print('{} has occurred {} times'.format(x,
count_item(lst, x)))
Output of the above code:
e has occurred 3 times
Python count occurrences of all items in list using for loop
We can count the frequency of each element in a list using a for loop and a dictionary. We create an empty dictionary that will contain unique elements from the input list as keys and their counts as values. First, we initialise the list with elements and an empty dictionary, and then iterate over the list of elements. Inside the loop, we check whether the element is present in the dictionary or not. If the element is already present in the dictionary, then increase its count. And, if the element is not present in the dictionary, then initialise its count with 1.
# Python program to count the frequency of
# elements in a list using a dictionary
# initializing list
x_list = ['23', '23', '42', '27', '42', '27', '27', '71', '62']
dictionary = {}
# iterating over the list
for item in x_list:
# checking the element in dictionary
if item in dictionary:
# incrementing the counr
dictionary[item] += 1
else:
# initializing the count
dictionary[item] = 1
# printing the frequency
print(dictionary)
Output of the above code:
{'23': 2, '42': 2, '27': 3, '71': 1, '62': 1}
Python count occurrences of all items in list using countof() method
The countOf() method is used for counting the number of occurrences of the element from the lists. It counts the number of occurrences of a given value.
Syntax-Operator.countOf(freq = a, value = b)
Here, a is a list or a string, and b is a value for which we have to count the number of occurrences. First, we need to import the operator module to use this method.
In the given Python program, we import the operator module and define a and b. Next, we obtain the count of b in a using the countOf() method and print the result.
# Python code to count the number of occurrences
import operator as op
x_lst = ['a','a','c','d','c','e','d','e','e']
print('{} has occurred {} times'.format('a',
op.countOf(x_lst,"a")))
print('{} has occurred {} times'.format('c',
op.countOf(x_lst,"c")))
print('{} has occurred {} times'.format('d',
op.countOf(x_lst,"d")))
print('{} has occurred {} times'.format('e',
op.countOf(x_lst,"e")))
Output of the above code:
a has occurred 2 times
c has occurred 2 times
d has occurred 2 times
e has occurred 3 times
Python count occurrences of all items in list using collections module
The Collections module in Python contains containers which are used to store collections of data, for example, lists, dicts, sets, tuples, etc. First, install the collections module using the following command.
In the given example, we import the collection module and initialise the list with elements. The Python Counter class is part of the Collections module. It is a subclass of the dictionary. It stores elements as dictionary keys, and their counts are stored as dictionary values. By using this, we can get the frequency of each element in a list. Finally, we convert the result to a dictionary using the dict and print the frequency.
# Python program to count the frequency of
# elements in a list using collections module
# importing the module
import collections
# initializing list
x_list = [31,23,54,31,22,23,54,90,23]
# using Counter to find frequency of elements
frequency = collections.Counter(x_list)
# printing the frequency
print(dict(frequency))
Output of the above code:
{31: 2, 23: 3, 54: 2, 22: 1, 90: 1}
Python count occurrences of given item in list using collections module
In the given Python program, we count the occurences of a given item in a list using the collections module.
# Python program to count the frequency of
# elements in a list using collections module
# importing the module
from collections import Counter
# initializing list
x_list = [31,23,54,31,22,23,54,90,23]
# using Counter to find frequency of elements
counts = Counter(x_list)
print('{} has occurred {} times'.format(31,counts[31]))
print('{} has occurred {} times'.format(23,counts[23]))
print('{} has occurred {} times'.format(54,counts[54]))
Output of the above code:
31 has occurred 2 times
23 has occurred 3 times
54 has occurred 2 times
Python count occurrences of items in list using pandas library
Python Pandas is an open source, fast, easy-to-use tool for data manipulation and data analysis. In the given Python program, we count the occurrences of items in the list using the pandas library.
# Python program to count the frequency of
# elements in a list using pandas module
# importing the module
import pandas as pd
# initializing list
x_list = [13,23,54,13,22,23,54,90,13]
# find frequency of elements
counts = pd.Series(x_list).value_counts()
print('{} has occurred {} times'.format(13,counts[13]))
print('{} has occurred {} times'.format(23,counts[23]))
print('{} has occurred {} times'.format(54,counts[54]))
Output of the above code:
13 has occurred 3 times
23 has occurred 2 times
54 has occurred 2 times
Related Articles
Python Convert String to UppercaseConvert string to int Python
Python program to reverse a string
Count consonants in a string Python
Python split strings by comma
Count vowels in a string Python
Convert string to lowercase Python
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Python iterate list with index
Convert List to Dataframe Python
numpy random choice
Dictionary inside list python
Strip function in Python
Python raise keyword
Check if two strings are anagrams Python
Python program to map two lists into a dictionary