Better Programming

Advice for programmers.

Follow publication

Member-only story

Count Items in Python With the Help of Counter Objects

Yong Cui
Better Programming
Published in
7 min readAug 7, 2020

--

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:

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:

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.
  • 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.

Is there another, better way to solve the problem? If you know Python, you should guess that the answer is yes. The Counter class is specifically designed to count elements in these data structures.

--

--

Yong Cui
Yong Cui

Written by Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).

No responses yet

Write a response