list.count()

Counts how many times a value occurs in a list.

Returns
The number of occurrences.
Changes the original
No
On this page

Example

#
Python
answers = ["A", "C", "A", "B", "A"]

print(answers.count("A"))
print(answers.count("D"))
print([1, 1.0, True].count(1))
Resultsaved result, you can check it
3
0
3

Definition and usage

#

The count(x) method returns the number of items equal to x. When the value is not in the list, the result is 0.

The comparison uses ==, so 1 and 1.0 are treated as equal, and True counts as 1.

To count every distinct value at once, collections.Counter is a better choice, since it does it in a single pass instead of calling count() for each value.

Syntax

#
Syntax
list.count(value)

Parameters

#
  • value

    any value

    The value to count.

Good practices

#
  • To count every value, use Counter(my_list).
  • Remember that True == 1 in Python, which affects counting in lists with mixed types.

Related entries

#

Spotted a mistake or missing an example? Write to us.