Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

Counter Python: Count Items in a List

  • Vijaykrishna RamVijaykrishna Ram
  • November 10, 2026
  • Python Programming
Counter Python: Count Items in a List

Counting the frequency of each value in a Python list gives you a tally of repeated and one-off items. Python’s collections.Counter builds that tally from an iterable, storing each hashable value with its count.

I’ll show how to build and update a Counter, then explain when list.count() is a better fit.

TL;DR

Use collections.Counter to turn an iterable into a mapping of each hashable value to its frequency.

  • Import it with from collections import Counter and pass a list, string or other iterable.
  • Use most_common(n) for the top results, and update() to add more observations.
  • Use list.count(value) when you need only one value’s frequency.

What Is a Counter in Python?

Counter is a class in Python’s standard-library collections module. It is a dictionary subclass that stores each distinct, hashable element as a key and its frequency as the value.

A frequency is the number of times a value appears. Pass an iterable such as a list or string to count its elements.

For text analysis, decide how to split text into words. A string passed directly to Counter counts characters. This means spaces and punctuation are also counted if they remain in the string.

A mapping constructor can combine a tally produced elsewhere with another batch. If the input is a list of pairs, convert it to a dictionary first when each pair represents an element and its count. Passing pairs directly counts each pair as an item instead, which often surprises readers working with grouped data.

How to Count Items with Counter Step by Step

Import the class, give it the values to count, then inspect the resulting key-count pairs. The same object can answer a missing-value check and return a ranked list.

Step 1: Create a Counter from an iterable

I ran python3 counter_demo.py on a list of six words. It printed Counter({‘red’: 3, ‘blue’: 2, ‘green’: 1}), so repeated values become counts and unique values remain present once as keys.

from collections import Counter

words = "red blue red green blue red".split()
counts = Counter(words)
print(counts)
print(counts.most_common(2))
print(counts["purple"])

try:
    Counter([["red"], ["blue"]])
except TypeError as error:
    print(type(error).__name__ + ": " + str(error))

items = ["red", "blue", "red", "green"]
print(Counter(items) == {"red": 2, "blue": 1, "green": 1})
print(items.count("red"), Counter(items)["red"])

The output shows the ranked frequencies, a zero for an absent key and the input error below:

Counter({'red': 3, 'blue': 2, 'green': 1})
[('red', 3), ('blue', 2)]
0
TypeError: unhashable type: 'list'
True
2 2
Terminal output showing Python Counter frequencies and an unhashable list error

The absent key purple reads as zero. The final line compares list.count() with the tally for one value. Both return two for this input.

Step 2: Read the top counts

most_common(n) returns up to n pairs, ordered from the greatest count to the least. With no argument, it returns all stored entries. In the run above, most_common(2) returned red with three and blue with two.

Equal counts follow encounter order in current Python documentation. For a single statistical mode, Python’s statistics.mode() expresses that question directly. multimode() returns tied modes.

Step 3: Add another batch

Call update() with another iterable to add its frequencies to the existing tally. Passing a mapping adds its values as counts, which differs from counting the mapping’s keys. For example, adding a batch with blue twice and yellow once increases those totals without removing the earlier red and green entries.

Counter Edge Cases and Method Choices

Choose the operation based on the shape of the input and whether you need every frequency or one answer. These differences prevent common type errors and misleading results.

Unary plus creates a Counter containing only positive counts after signed arithmetic. Delete a key when it should no longer appear in membership checks.

I passed nested lists to Counter and got TypeError: unhashable type: ‘list’. Convert each list to a tuple when its values can serve as immutable keys.

CaseBehaviorWhat to do
Unhashable keyNested list raises TypeErrorUse a tuple key when appropriate
Zero or negative countelements() omits itUse subtract() if signed differences must remain
One value lookuplist.count(value) scans the sequenceUse Counter when several frequencies are needed

For one requested value, items.count(value) scans a list. Counter builds a tally for the full iterable in one pass, which helps when you query several values.

Runtime depends on input size and key behavior, so measure the workload before comparing speed.

most_common() returns a list and does not reorder the Counter object. To create a separately sorted list, sort its items().

For word tallies, normalize capitalization before counting when case should not distinguish entries. Counter treats each supplied token as distinct.

See Text Mining Python for broader text work and Python standard-library modules for related built-ins.

Conclusion

Counter provides a compact way to retain a frequency table for later lookups. Check Python’s Counter documentation for supported methods and arithmetic.

FAQ

These quick answers cover the common counting questions that remain after the examples.

How do I import Counter in Python?

Use from collections import Counter. It is part of Python’s standard-library collections module.

How do I count characters in a string?

Pass the string to Counter, such as Counter(‘banana’). This counts each character, including spaces and punctuation.

How do I sort a Counter by count?

Call most_common() for descending count order, or sort counter.items() for an explicit sorted list of pairs.

Vijaykrishna Ram
Vijaykrishna Ram
Articles: 99
One Hot Encoding in Python
Previous Post One Hot Encoding in Python
Next Post Python Logarithm Base 2 Using NumPy log2()
Python Logarithm Base 2 Using NumPy log2()

Related Posts

What Does %s Mean in Python String Formatting?

What Does %s Mean in a Python Format String?

  • November 30, 2026
Python Convert String to List

Python Convert String to List: Choose the Right Method

  • November 29, 2026
Translate String Python

Translate String Python

  • November 29, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.