# Python Counter with Example & Python Collections Type

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Earlier, we discussed three classes from Python module collections. Today, weâ€™ll talk about another such class- Python Counter. Here, we will study initializing, updating, accessing, and reassigning counters in Python.

Moreover, we will learn Python counter list, loops and arithmetic.

So, let’s start the Python Counter Tutorial.

Python Counter with Example & Python Collections Type

## What is Python Counter?

Python Counter, like the other three containers we mentioned above, is a subclass of â€˜dictâ€™. It keeps a count of the number of occurrences of any value in the container.

Simply speaking, if you add the value â€˜helloâ€™ thrice in the container, it will remember that you added it thrice. So, Counter counts hashable objectsÂ inÂ Python.

Lets see this Python Counter example.

```>>> from collections import Counter
>>> c=Counter(['a','b','c','a','b','a'])
>>> c```

Output

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})
`>>> c['a']`

Output

3
`>>> issubclass(Counter,dict)`

Output

True

Now, letâ€™s take a look atÂ python counter syntax.

### Initializing a Python Counter

To initialize or define a counter in python, we use the counter factory function. Yet, in that, we can do it in three ways:

#### 1. Using a List or Similar Containers

We can pass Python list of values to Counter(). Every time it encounters a value again, it raises its count by 1.

```>>> c=Counter(['a','b','c','a','b','a'])
>>> c```

Output

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

As you can see, it could recognize that there are three â€˜aâ€™s in the list in python, two â€˜bâ€™s, and one â€˜câ€™.
We can also useÂ Python tuple.

```>>> c=Counter(('a','b','c','a','b','a'))
>>> c```

Output

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

Or, you can pass it Python string.

```>>> c=Counter("Hello")
>>> c```

Output

Counter({‘l’: 2, ‘H’: 1, ‘e’: 1, ‘o’: 1})

Python string is a container too, remember? Also, it displays the counts in a descending order.

But when we use a Set, it only holds every value once. So, it does not make sense to use Counter() with Python Set.

```>>> c=Counter({'a','b','c','a','b','a'})
>>> c```

Output

Counter({‘a’: 1, ‘c’: 1, ‘b’: 1})

#### 2. Using a Python Dictionary

We can also manually tell the Python Counter the count of values, using a dictionary in Python.

```>>> c=Counter({'a':3,'b':2,'c':1})
>>> c```

Output

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

#### 3. Using Keyword Arguments

Finally, we can use keyword arguments to manually tell Counter() the count.

```>>> c=Counter(a=3,b=2,c=1)
>>> c```

Output

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

### Updating a Python Counter

Like it is with every other container, we can first declare an empty Python Counter and then populate it. We perform the update calling the update() method on the Counter.

```>>> d=Counter()
>>> d.update("Hello")
>>> d```

Output

Counter({‘l’: 2, ‘H’: 1, ‘e’: 1, ‘o’: 1})

We updated it once; we can update it further, in a different way if we want.

```>>> d.update({'e':2,'o':4})
>>> d```

Output

Counter({‘o’: 5, ‘e’: 3, ‘l’: 2, ‘H’: 1})

Here, we told Python Counter that weâ€™re adding two more â€˜eâ€™s and four more â€˜oâ€™s. Then, when we accessed it, it printed the counts in a descending order.

### Accessing Counts in Python

We can access the count for a particular value simply by using it as an index to the Python Counter we defined.

`>>> d['e']`

Output

3

Letâ€™s try displaying the counts of values in a string, with Python counter that takes a different string as an argument.

```>>> e=Counter("Hello")
>>> for i in "Help": Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
print(f"{i}: {e[i]}") Â  Â  Â Â  Â
H: 1
e: 1
l: 2
p: 0```

From this, we interpret that in Python Counter e, â€˜Hâ€™ has a count of 1, â€˜eâ€™ has a count of 1, â€˜lâ€™ has 2, and â€˜pâ€™ has none(hence, 0).

From this, we conclude that if a key doesnâ€™t exist, it will consider its count to be 0, instead of raising a KeyError.

`>>> e['q']`

To compare, letâ€™s also see how this would fair in a regular dictionary.

```>>> dict1={'H':1,'e':1,'l':2,'o':1}
>>> dict1['p']
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
dict1['p']```

Output

KeyError: ‘p’

#### 1. The elements() Method

Or, we could use the elements() method, which returns an iterator object for the values in the Counter. We can use this with a Python for-loop.

```>>> e=Counter({'a':3,'b':2,'c':1,'d':0})
>>> for i in e.elements():
Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â  print(f"{i}: {e[i]}")
a: 3
a: 3
a: 3
b: 2
b: 2
c: 1
>>> e.elements()```

Output

<itertools.chain object at 0x06336390>

Weâ€™ll discuss python itertools in a later lesson.

#### 2. Accessing the Most Common Values

To get n most-common values (the ones with the highest frequencies), we call the method most_common().

`>>> e.most_common(2)`

Output

[(‘a’, 3), (‘b’, 2)]

`>>> e.most_common(4)`

Output

[(‘a’, 3), (‘b’, 2), (‘c’, 1), (‘d’, 0)]

When we call it without any argument, however, we get all the items. So, it is the same as calling it with an argument with a value equal to the number of elements in Python counter.

`>>> e.most_common()`

Output

[(‘a’, 3), (‘b’, 2), (‘c’, 1), (‘d’, 0)]

### Reassigning Counts in Python

Of course, Python Counters arenâ€™t immutable. You can reassign a count the following way:

```>>> e['e']=5
>>> e```

Output

Counter({‘e’: 5, ‘l’: 2, ‘H’: 1, ‘o’: 1})

To clear a Python counter, we use clear().

```>>> b.clear()
>>> b```

Output

Counter()

### Python Counter Arithmetic

Finally, weâ€™ll discuss some Counter arithmetic in Python.
To aggregate results, we can perform arithmetic and set operations on Python Counters. Letâ€™s take two sample Counters for exemplary purposes.

```>>> a=Counter({'a':3,'b':2,'c':1})
>>> b=Counter({'c':3,'d':2,'e':1})```

Now, sit back and watch it unfold.

`>>> a+b`

Output

Counter({‘c’: 4, ‘a’: 3, ‘b’: 2, ‘d’: 2, ‘e’: 1})

`>>> a-b`

Output

Counter({‘a’: 3, ‘b’: 2})

`>>> b-a`

Output

Counter({‘c’: 2, ‘d’: 2, ‘e’: 1})

Here, a-b does not have â€˜câ€™, because 1-3=-2. A negative count does not mean anything. Likewise, b-a has â€˜câ€™ with a count of 2, because 3-1=2. We can also do this calling the subtract() method.

```>>> a.subtract(b)
>>> a```

Output

Counter({‘a’: 3, ‘b’: 2, ‘e’: -1, ‘c’: -2, ‘d’: -2})

This way, it gives us negative counts if it has to.
Now, look at the following code:

`>>> a.__add__(b)`

Output

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

`>>> a&b`

Output

Counter({‘c’: 1})

`>>> a|b`

Output

Counter({‘a’: 3, ‘c’: 3, ‘b’: 2, ‘d’: 2, ‘e’: 1})

Here, a|b has a count of 3 for â€˜câ€™, because that is what OR does.

```>>> a=Counter({'e':-1})
>>> -a```

Output

Counter({‘e’: 1})

Check out the result for dir(Counter), and try to apply all of those methods to your Counters in Python.

### Python Interview Questions on Python Counter

1. What is a counter in Python?
2. What does counter () do in Python?
3. How do you write a count function in Python?
4. How do you increment a counter in Python?
5. How do you make a time counter in Python?

## Conclusion

Python Counter is a container that keeps track of the number of occurrences of a value. Today, we looked at methods like update(), most_common(), clear(), elements(), and subtract().

In our next lesson, weâ€™ll revise all these four classes in brief.

You give me 15 seconds I promise you best tutorials