Technical skill practice

count in Python: Count a Value or a Nonoverlapping Substring

Python count methods answer occurrence questions. list.count(value) counts list entries equal to that value. str.count(text) counts nonoverlapping occurrences of a substring. Neither is a replacement for len when you want the container’s total size.

Start with a small, explicit task

Count accepted responses in a fictional feedback sequence, then inspect the substring ana in banana. There are two starting positions where those letters can be seen, but they overlap. Predict the built-in text count before running it, and compare the result with a simple repeated-letter count.

Run the complete example

This original example was checked with Python 3.12.14. Save it as python_count.py and run it with Python 3.12. It uses only the standard library. The assertions check the stated results.

Expected output

yes: 3 total: 5

ana: 1 a: 3

a in [2:5]: 1

responses = ["yes", "no", "yes", "later", "yes"]
yes_count = responses.count("yes")
text = "banana"
assert yes_count == 3 and len(responses) == 5
assert responses.count("missing") == 0
assert text.count("ana") == 1
assert text.count("a") == 3
assert text.count("a", 2, 5) == 1
print("yes:", yes_count, "total:", len(responses))
print("ana:", text.count("ana"), "a:", text.count("a"))
print("a in [2:5]:", text.count("a", 2, 5))

Explain the result

The list has five responses but only three equal yes. A missing value contributes zero occurrences without raising an error. That differs from list.index, which is a position lookup and fails when no match exists. The two methods should not be used interchangeably when validating input.

banana has three individual a characters, but its two visible ana fragments overlap at one character. str.count counts nonoverlapping matches, yielding one. The bounded call examines positions 2 through 4, which form nan and contain one a; the stop index 5 is excluded. These results are case-sensitive literal comparisons.

Avoid these mistakes

Calling count repeatedly for every distinct item walks the data repeatedly; a frequency table such as Counter can be clearer when you need all values. Also decide what an occurrence means before counting: literal nonoverlapping substrings, overlapping patterns and tokenized words are different tasks.

Questions, answered

Why does banana.count("ana") return one?

The potential matches overlap, and str.count counts nonoverlapping occurrences.

How do I count all list items?

Use len for total size. list.count requires the particular value whose occurrences you want.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.