A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-find-all-elements-count-in-list/ below:

Python - Find all elements count in list

Python - Find all elements count in list

Last Updated : 11 Jul, 2025

In Python, counting the occurrences of all elements in a list is to determine how many times each unique element appears in the list. In this article, we will explore different methods to achieve this. The collections.Counter class is specifically designed for counting hashable objects. It provides a fast and intuitive way to count occurrences in a list.

Python
from collections import Counter

a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

c = Counter(a)
print(dict(c))

Output
{1: 1, 2: 2, 3: 3, 4: 4}

Explanation:

Let's explore some more methods to find all elements count in list.

Using a Dictionary with a Loop

If we want to avoid using external libraries, we can use a dictionary to count occurrences manually.

Python
counts = {}
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

for element in a:
    counts[element] = counts.get(element, 0) + 1

print(counts)

Output
{1: 1, 2: 2, 3: 3, 4: 4}

Explanation:

Using List Comprehension with count()

List comprehension combined with the count() method can also be used to count occurrences.

Python
a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

counts = {element: a.count(element) for element in set(a)}

print("Element Counts:", counts)

Output
Element Counts: {1: 1, 2: 2, 3: 3, 4: 4}

Explanation:

  1. set(a) ensures that we only iterate over unique elements in the list.
  2. a.count(element) counts the occurrences of each element.
  3. A dictionary comprehension is used to create a dictionary with element counts.
Using pandas.Series.value_counts

If we are already using the Pandas library, the value_counts() method offers a convenient way to count occurrences. This method is more suitable for data analysis tasks.

Python
import pandas as pd

a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

counts = pd.Series(a).value_counts().to_dict()

print("Element Counts:", counts)

Output
Element Counts: {4: 4, 3: 3, 2: 2, 1: 1}

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4