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.
- Type the following code into the notebook — pressing Enter after each line:
from collections import CounterMyList = [1, 2, 3, 4, 1, 2, 3, 1, 2, 1, 5]ListCount = Counter(MyList)print(ListCount)for ThisItem in ListCount.items():print("Item: ", ThisItem[0]," Appears: ", ThisItem[1])print("The value 1 appears {0} times.".format(ListCount.get(1)))To use the
Counterobject, you must import it fromcollections. Of course, if you work with other collection types in your application, you can import the entirecollectionspackage 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 newCounterobject,ListCount. You can createCounterobjects 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
ListCountin various ways. The first output is theCounteras it appears without any manipulation. The second output prints the individual unique elements inMyListalong with the number of times each element appears. To obtain both the element and the number of times it appears, you must use theitems()function as shown. Finally, the example demonstrates how to obtain an individual count from the list by using theget()function. - Click Run Cell.Python outputs the results of using the
Counterobject.
Notice that the information is actually stored in the
Counteras a key and value pair. The element found inMyListbecomes a key inListCountthat identifies the unique element name. The value contains the number of times that that element appears withinMyList.


