Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Lists, Tuples and Ranges

Python list.count() method

Reference for Python list.count(): count how many times a value appears in a list, how equality is decided, performance, and when Counter is the better tool.

The count() method returns how many items in the list are equal to the value you pass. It scans the whole list from start to end and returns an integer, which is 0 when the value is not present. It never raises an error for a missing value.

Use it for a quick tally of one value. If you need counts for many different values, collections.Counter does it in a single pass.

Python
print([1, 2, 2, 3, 2].count(2))   # 3

Try it

Python Counting values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Many values: use Counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
list.count(value)
Name Description
value The object to look for. Items are compared to it with ==.

Return value: an int, the number of matching items (0 or more).

Raises: nothing for a missing value.

Usage notes

  • Equality, not identity. Items match when item == value is true (identity is checked first as a shortcut), so 1, 1.0 and True all count as the same value, while "1" does not.
  • Nested lists compare by content. [[1, 2], [1, 2]].count([1, 2]) is 2.
  • Linear time. Every call walks the entire list. Calling count() for each distinct item inside a loop is O(n squared); use Counter instead.
  • Counting by a condition. For "how many items are greater than 2" use sum(1 for x in data if x > 2); count() only compares for equality.
  • NaN. float("nan") is never equal to anything, even itself, but a nan that is the very same object is found by the identity shortcut. Treat counting NaNs with math.isnan() instead.
  • Same method on other types: tuple.count() and str.count(sub) exist. The string version counts non-overlapping substrings and accepts start and end; the list version takes no range.
  • Presence only? If you only need to know whether a value exists, use value in items, which stops at the first match.