What is the Counter subclass in Python and how to use it
Python’s Counter
class is used to count elements in a container. It’s a subclass of Dictionary and can be combined with different methods.
What is Python’s Counter
subclass?
A subclass of Dictionary, Python’s Counter
is a useful tool that counts how frequently elements occur in a list. While this task can be done manually if you have a short sequence of values, for larger datasets, counting can quickly become complicated.
Python’s Counter
is an integer variable that starts with an initial value of zero. A single counter provides the frequency for one object. If you want to take multiple different objects into account, you need to use a separate counter for each.
The Counter
class can be applied to lists, Python tuples, dictionaries und Python strings. The syntax for Counter
looks like this:
Counter(list)
python- 99.9% uptime
- PHP 8.3 with JIT compiler
- SSL, DDoS protection, and backups
How to use Python Counter
In the following sections, we’ll show you some simple examples of how to use Python Counter
.
Using Python Counter
with a list
In this example, we’re going to create a simple list that contains different values.
List = ['a', 'a', 'b', 'a', 'c', 'b', 'b', 'c', 'a', 'c', 'b', 'c', 'c']
pythonThe list has three different elements: ‘a’, ‘b’ and ‘c’. To find out how frequently each of these elements appears in the list, we’ll use Python Counter
. The output looks like this:
Counter({'c' : 5, 'a' : 4, 'b' : 4})
pythonBefore you can use Python Counter
, you have to import it. To have the result displayed on your screen, you need to use the print()
function. Below, you’ll see everything you need to include in your code to display the output from above on your screen:
from collections import Counter
List = ['a', 'a', 'b', 'a', 'c', 'b', 'b', 'c', 'a', 'c', 'b', 'c', 'c']
counter_list = Counter(List)
print(Counter(List))
pythonNow, you should see the following output:
Counter({'c' : 5, 'a' : 4, 'b' : 4})
pythonUsing Counter
with a tuple
The next example is similar to the first one, but this time we’re going to use Python Counter
with a tuple. Tuples are used in Python to store multiple values in a single variable. Since a tuple is an ordered collection of objects, the order of the objects will be taken into account. Objects are separated by commas and enclosed in parentheses. Here’s what the code looks like:
from collections import Counter
Tuple = ('a', 'a', 'b', 'a', 'c', 'b', 'b', 'c', 'a', 'c', 'b', 'c', 'c')
print(Counter(Tuple))
pythonThe result is the same as in the previous example:
Counter({'c' : 5, 'a' : 4, 'b' : 4})
pythonUsing Counter
with Dictionary
In a dictionary, elements are stored inside of curly brackets as key-value pairs. Applying Python Counter
to a dictionary converts the dictionary into a hashtable object. With numerical values, the elements become keys, and their corresponding values become the number of times the keys appear in the dictionary. Using the data from our previous example, this is what the code would look like:
from collections import Counter
Dictionary = {'a' : 4, 'b' : 4, 'c' : 5}
counter_dictionary = Counter(Dictionary)
print(Counter(Dictionary))
pythonThe output is the same:
Counter({'c' : 5, 'a' : 4, 'b' : 4})
pythonGet to the finish line in just three simple steps: With Deploy Now, you can seamlessly connect your repository to IONOS’ platform, automate builds and access a reliable infrastructure. Benefit from expert advice and rates that correspond to your development needs.
Combining Python’s Counter
with a string
To get an idea of how much time and effort you can save with Python’s Counter
, you should try using it with a string. A string is simply a sequence of characters (including spaces) enclosed in quotation marks. Let’s take a look at how this works:
from collections import Counter
String = "This is an example."
counter_string = Counter(String)
print(Counter(String))
pythonIn the code above, Counter
counts how many times each character occurs in the string above. Here’s the output:
Counter({' ': 5, 'e': 3, 's': 3, 'a': 2, 'i': 2, 'T': 1, 'h': 1, 't': 1, 'n': 1, 'm': 1, 'p': 1, '.': 1})
pythonUsing .update()
to make changes
Python Counter
comes with lots of different features. One useful feature is the ability to add new data to an existing count. You can do this with the .update()
method, which allows you to add additional counts to an existing counter. Here’s a simple example that uses the same approach as above but without specifically assigning “blue” to a string variable.
from collections import Counter
Counter("blue")
print(Counter(String))
pythonHere’s the output:
Counter({'b': 1, 'l': 1, 'u': 1, 'e': 1})```
Now, let’s use `.update()`:
```python
from collections import Counter
colors = Counter({'b': 1, 'l': 1, 'u': 1, 'e': 1})
colors.update("gray")
print(colors)
pythonAfter applying .update()
, the output is updated to:
Counter({'e': 2, 'a': 1, 'r': 1, 'g': 1, 'b': 1, 'l': 1, 'y': 1})
pythonAccessing values in Python Counter
Since Python Counter
works in a manner similar to Dictionary
, you can also access values in a counter. Below are some examples showing different ways you can access data. Letters serve as keys and their frequencies as values.
from collections import Counter
letters = Counter("rooftop")
letters["r"]
1
letters["o"]
3
pythonfor letter in letters:
print(letter, letters[letter])
r 1
o3
f 1
t 1
p 1
pythonHere’s what happens when the method .keys()
is used:
for letter in letters.keys():
print(letter, letters[letter])
r 1
o3
f 1
t 1
p 1
pythonHere’s an example with .values()
:
for count in letters.values():
print(count)
1
3
1
1
1
pythonHere’s the .items()
method:
for letter, count in letters.items():
print(letter, count)
r 1
o3
f 1
t 1
p 1
pythonDeleting elements from Counter
If you want to delete an element from a counter in Python, you can use the del
statement:
from collections import Counter
example = {'b' : 1, 'l' : 1, 'u' : 1, 'e' : 1}
del example["b"]
print(Counter(example))
pythonYour output will now look like this:
Counter({'l' : 1, 'u' : 1, 'e' : 1})
pythonExcluding null values and negative values
You use the following code for Python Counter
to remove null or negative values:
from collections import Counter
values = Counter(a=6, b=0, c=1, d=-4)
values = +values
print(values)
pythonThe output for this is:
Counter({'a' : 6, 'c' : 1})
pythonDetermining the most frequent element using most_common(n)
Using most_common(n)
with Python Counter
, you can easily determine which elements are the most or least frequent. In the following example, we’re going to use a product that comes in various colors and track how many units of each color are in stock. If a number is negative, it means the color is out of stock but has already been preordered by a customer. To find out which color has the most units available, we can use the following code:
from collections import Counter
color_variants = Counter({'blue' : 2, 'gray' : -1, 'black' : 0})
most_units = color_variants.most_common(1)
print(most_units)
pythonThe output is:
[('blue' : 2)]
pythonTo find out which color has the fewest units, you can adjust the code by doing the following:
from collections import Counter
color_variants = Counter({'blue' : 2, 'gray' : -1, 'black' : 0})
fewest_units = color_variants.most_common()[:-2:-1]
print(fewest_units)
pythonThis gives you:
[('gray' : -1)]
pythonSorting file types according to frequency
Another useful feature of the Counter
class is its ability to count the different types of files in a directory. To get a better idea of how this works, let’s imagine we have a folder named “Images”. This folder contains various files in different formats. To sort and count these files according to their format, we’re going to use the following code:
import pathlib
from collections import Counter
directory_path = pathlib.Path("Images/")
extensions = [entry.suffix for entry in directory_path.iterdir() if entry.is_file()]
extension_counter = Counter(extensions)
print(extension_counter)
pythonArithmetic with Python Counter
You can also do arithmetic operations with Python’s Counter
. It’s important to note, however, that only positive values are included in the output. In the following code, we’ll take a look at how to do some basic arithmetic with Counter
.
Addition:
from collections import Counter
x = Counter(a=4, b=2, c=1)
y = Counter(a=2, b=1, c=2)
z = x + y
print(z)
pythonCounter({'a' : 6, 'b' : 3, 'c' : 3})
pythonSubtraction:
from collections import Counter
x = Counter(a=4, b=2, c=1)
y = Counter(a=2, b=1, c=2)
z = x - y
print(z)
pythonCounter({'a' : 2, 'b' : 1})
pythonSince the value for c is negative, it isn’t included in the output.
There’s lots more to learn about Python in our Digital Guide. For example, you can find articles on installing Python, Python basics and Python operators.