Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge
  • All
  • C#
  • MVC
  • Web API
  • Azure
  • IIS
  • JavaScript
  • Angular
  • Node.js
  • Java
  • Python
  • SQL Server
  • SEO
  • Entrepreneur
  • Productivity

How to count the occurrences of list items in Python?

Use the list.count() method of the built-in list class to get the number of occurrences of an item in the given list.

Example: Count List Items
names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
nm=input('Enter name to count: ')
count=names.count(nm)
print('count = ', count)
Output
Enter name to count: John count =  2

Count Occurences of Each Item in List

We need two nested for loops to count the occurrences of each item in the list. Name at i'th positional index - i being variable controlling outer loop, is searched for occurrence in remaining list iterated with j variable. The current name and its count are added in a dictionary, only if the name is not previously present in it as a key.

Example: Count Occurences of Each Item in List
names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
<pre className="language-python"><code>names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
d={}
for i in range(len(names)-1):
    x=names[i]
    c=0
    for j in range(i,len(names)):
        if names[j]==names[i]:
            c=c+1
    count=dict({x:c})
    if x not in d.keys():
        d.update(count)
print (d)
Output
{'Deepak': 3, 'Reema': 3, 'John': 2, 'Munna': 1, 'Amit': 1}

Again, we can use the count() method to make the solution more concise.

Example: Count Occurences of Each Item in List
names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
<pre className="language-python"><code>names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
d={}
for i in range(len(names)-1):
    x=names[i]
    c=0
    for j in range(i,len(names)):
        c=names.count(x)
    count=dict({x:c})
    if x not in d.keys():
        d.update(count)
print (d)
Output
{'Deepak': 3, 'Reema': 3, 'John': 2, 'Munna': 1, 'Amit': 1}

However, this solution is not an efficient one. The occurrence of an item is counted as many times it appears in the list, thereby increasing the processing time, especially for a list with a large number of items.

To counter this problem, we first create a collection of unique items in the given list. Pythton's Set object is a collection of unique items.

Example: Convert List to Set
names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
<pre className="language-python"><code>names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
nameset=set(names)
print(nameset)
Output
{'Reema', 'Munna', 'Amit', 'Deepak', 'John'}

Now we can count the occurrence of a set items in the list and construct the dictionary object. However, this time we will use list comprehension instead of regular for loop as we used above.

Example: Count Occurences of Each Item in List
names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
nameset=set(names)
d={name:names.count(name) for name in nameset}
print(d)
Output
{'Reema': 3, 'Munna': 1, 'Amit': 1, 'Deepak': 3, 'John': 2}

Count Occurences of Each Item in List using Collection Module

The collection module in Python's standard library defines many specialized container data types. One of them is a Counter class. It is a dict subclass that helps in the giving count of the hashable items (such as list or dictionary).

Example: Count Occurences of Each Item in List using Counter()
from collections import Counter

names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
d=dict(Counter(names))
print (d)
<pre className="language-python"><code>from collections import Counter

names=['Deepak','Reema','John','Deepak','Munna','Reema','Deepak','Amit','John','Reema']
d=dict(Counter(names))
print (d)
Output
{'Deepak': 3, 'Reema': 3, 'John': 2, 'Munna': 1, 'Amit': 1}

Note that, above, a Counter object is typecasted to a regular dictionary object to display the result.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.