By John Paul Mueller

Sometimes you have a data source and you simply need to know how often things happen in Python (such as the appearance of a certain item in the list). When you have a short list, you can simply count the items. However, when you have a really long list, getting an accurate count is nearly impossible. For example, consider what it would take if you had a really long novel like War and Peace in a list and wanted to know the frequency of the words the novel used. The task would be impossible without a computer.

The Counter object lets you count items quickly. In addition, it’s incredibly easy to use. This example creates a list with repetitive elements and then counts how many times those elements actually appear.

  1. Type the following code into the notebook — pressing Enter after each line:
    from collections import Counter

    MyList = [1, 2, 3, 4, 1, 2, 3, 1, 2, 1, 5]
    ListCount = Counter(MyList)
    for ThisItem in ListCount.items():
    print("Item: ", ThisItem[0],
    " Appears: ", ThisItem[1])
    print("The value 1 appears {0} times."

    To use the Counter object, you must import it from collections. Of course, if you work with other collection types in your application, you can import the entire collections package by typing import collections instead.

    The example begins by creating a list, MyList, with repetitive numeric elements. You can easily see that some elements appear more than once. The example places the list into a new Counter object, ListCount. You can create Counter objects in all sorts of ways, but this is the most convenient method when working with a list.

    The Counter object and the list aren’t actually connected in any way. When the list content changes, you must re-create the Counter object because it won’t automatically see the change. An alternative to re-creating the counter is to call the clear() method first and then call the update() method to fill the Counter object with the new data.

    The application prints ListCount in various ways. The first output is the Counter as it appears without any manipulation. The second output prints the individual unique elements in MyList along with the number of times each element appears. To obtain both the element and the number of times it appears, you must use the items() function as shown. Finally, the example demonstrates how to obtain an individual count from the list by using the get() function.

  2. Click Run Cell.

    Python outputs the results of using the Counter object.

    Notice that the information is actually stored in the Counter as a key and value pair. The element found in MyList becomes a key in ListCount that identifies the unique element name. The value contains the number of times that that element appears within MyList.