python – The number of duplicate items in the list

Question:

There is an array with a bunch of duplicate elements. I need to display the contents of a specific element of this array and how many of the same elements are in it (output a number).
Array example:

array = ["Bob", "Alex", "Bob", "John"]  

(like 2 Bob, etc.)

Answer:

The easiest way to count the number of occurrences of all elements is to use the built-in Counter class from the collections module:

In [4]: from collections import Counter

In [5]: array = ["Bob", "Alex", "Bob", "John"] 

In [6]: c = Counter(array)

In [7]: c
Out[7]: Counter({'Bob': 2, 'Alex': 1, 'John': 1})

In [8]: c['Bob']
Out[8]: 2

In [9]: c['Unknown']
Out[9]: 0
Scroll to Top