 Go back

# Collections/Counter()

## Collections

Python has a builtin module named "collections". This module provides some useful collection data types that we can use. Before using any of these data types we must import collections.

``````import collections
``````

## Counter

Within the collections module there is a data type called a counter. The counter will count every instance of a certain element from any collection data type. We can create and use a new counter object like so:

``````import collections
from collections import Counter

c = Counter("hello")
print(c)

# This will print Counter({'h':1, 'e':1, 'l':2, 'o':1})
``````

The Counter object is similar to a dictionary. It will store as a key the letter and as the value the frequency of that key in the item it was passed.

Like dictionaries we can find the values associated with each key by typing the counter name and then the key enclosed in square brackets.

``````import collections

c = Counter("hello")
print(c["h"])

# This will print 1
``````

## Counter Methods

The Counter object has some useful methods that can be seen below.

.most_common(n): This will return the n most common items along with the amount of times they occur.

``````import collections
from collections import Counter

c = Counter([1,1,1,3,4,5,6,7, 7])

c.most_common(1)  # returns [(1, 3)]
c.most_common(2)  # returns [(1, 3), (7, 2)]
``````

.subtract(collection): This will subtract the count of items from the collection passed from the Counter object.

``````import collections
from collections import Counter

c = Counter([1,1,1,3,4,5,6,7, 7])
d = [1,1,3, 4, 4]

c.subtract(d)

print(c)  # prints Counter({1:1, 3:0, 4:-2, 5:1, 6:1, 7:2})
``````

.update(collection): This will add all of the counts of the collection to the Counter object.

``````import collections
from collections import Counter

c = Counter([1,1,1,3,4,5,6,7, 7])
d = [1,1,3]

c.update(d)

print(c)  # prints Counter({1:5, 3:2, 4:1, 5:1, 6:1, 7:2})
``````

.clear(): This will simply clear all of the counts from the Counter object.

``````import collections
from collections import Counter

c = Counter([1,1,1,3,4,5,6,7, 7])

c.clear()
print(c)  # prints Counter()
``````
Design & Development by 