Count Items in Python With the Help of Counter Objects
Count Items in Python With the Help of Counter Objects

The easy way to count objects in a data container

Photo by Djim Loic on Unsplash

The Premise

When we deal with data containers, such as tuples and lists, in Python we often need to count particular elements. One common way to do this is to use the count() function — you specify the element you want to count and the function returns the count.

Let’s take a look at some code for its use:

The count() function

As you can see above, we used the count() function with a list of scores.

One thing to note: When the elements specified in the function aren’t included in the list, we’ll get a count of zero, as expected. If we want to count the occurrences of all the elements, we’ll have to iterate them, as shown in the following code snippet:

Count All Elements

Several things are worth highlighting in the above:

To avoid counting elements of the same value, we use the set() constructor to convert these iterables to set objects. This means duplicate elements are removed — the for loop will only go over distinct elements to get their correct cumulative counts.

constructor to convert these iterables to set objects. This means duplicate elements are removed — the for loop will only go over distinct elements to get their correct cumulative counts. The count() function doesn’t only work with the list objects, it can also with tuples and strings. More generally, the count() function works with sequence data in Python, including strings, lists, tuples, and bytes.

As shown above, we have to use a for loop to iterate the elements to retrieve the counts for each individual element. It’s a bit tedious.
['Yong Cui']
['Python', 'Software Development', 'Technology', 'Data Science', 'Programming']