Counting Occurrences in a List in Python

Counting items is one of the most common tasks in Python — whether you’re tallying events, analyzing logs, or summarizing data.

 

Counting Occurrences in a List in Python

Counting items is one of the most common tasks in Python — whether you’re tallying events, analyzing logs, or summarizing data. A small dictionary‑based pattern gives you a clean, readable way to track how many times each item appears.

Source Code

items = ["apple", "banana", "apple", "orange", "banana", "apple"]

counts = {}

for item in items:
    counts[item] = counts.get(item, 0) + 1

# pseudocode:
# create an empty dictionary
# for each item in the list:
#     look up its current count (default to 0)
#     add 1 and store it back in the dictionary
  • Iteration — walks through each item in the list.
  • Lookupget() retrieves the current count or defaults to 0.
  • Update — increments the count and stores it back.
  • Result — produces a dictionary of item → count pairs.

Expected Output

# expected output
# before (a list): ["apple", "banana", "apple", "orange", "banana", "apple"]
# after  (a dictionary): {"apple": 3, "banana": 2, "orange": 1}

Counting with a dictionary is a foundational pattern: once you understand this idea, you can apply it to logs, events, tokens, words, API responses, and any data stream that needs summarizing.



Copyright © 2026 Tech-Reader.blog
All Rights Reserved

Popular posts from this blog

Insight: The Great Minimal OS Showdown—DietPi vs Raspberry Pi OS Lite

Running AI Models on Raspberry Pi 5 (8GB RAM): What Works and What Doesn't