# 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](https://www.ionos.co.uk/digitalguide/websites/web-development/python-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](https://www.ionos.co.uk/digitalguide/websites/web-development/python-tuples/), dictionaries und [Python strings](https://www.ionos.co.uk/digitalguide/websites/web-development/python-string/). The syntax for `Counter` looks like this:

```python
Counter(list)
```

## 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.

```python
List = ['a', 'a', 'b', 'a', 'c', 'b', 'b', 'c', 'a', 'c', 'b', 'c', 'c']
```

The 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:

```python
Counter({'c' : 5, 'a' : 4, 'b' : 4})
```

Before 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:

```python
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))
```

Now, you should see the following output:

```python
Counter({'c' : 5, 'a' : 4, 'b' : 4})
```

### Using `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 brackets. Here’s what the code looks like:

```python
from collections import Counter
Tuple = ('a', 'a', 'b', 'a', 'c', 'b', 'b', 'c', 'a', 'c', 'b', 'c', 'c')
print(Counter(Tuple))
```

The result is the same as in the previous example:

```python
Counter({'c' : 5, 'a' : 4, 'b' : 4})
```

### Using `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:

```python
from collections import Counter
Dictionary = {'a' : 4, 'b' : 4, 'c' : 5}
counter_dictionary = Counter(Dictionary)
print(Counter(Dictionary))
```

The output is the same:

```python
Counter({'c' : 5, 'a' : 4, 'b' : 4})
```

Tip Get to the finish line in just three simple steps: With [Deploy Now](https://www.ionos.co.uk/hosting/deploy-now "Deploy Now from IONOS"), 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:

```python
from collections import Counter
String = "This is an example."
counter_string = Counter(String)
print(Counter(String))
```

In the code above, `Counter` counts how many times each character occurs in the string above. Here’s the output:

```python
Counter({' ': 5, 'e': 3, 's': 3, 'a': 2, 'i': 2, 'T': 1, 'h': 1, 't': 1, 'n': 1, 'm': 1, 'p': 1, '.': 1})
```

### Using `.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.

```python
from collections import Counter
Counter("blue")
print(Counter(String))
```

Here’s the output:

```python
Counter({'b': 1, 'l': 1, 'u': 1, 'e': 1})```
Now, let’s use `.update()`:
```python
from collections import Counter
colours = Counter({'b': 1, 'l': 1, 'u': 1, 'e': 1})
colours.update("grey")
print(colours)
```

After applying `.update()`, the output is updated to:

```python
Counter({'e': 2, 'a': 1, 'r': 1, 'g': 1, 'b': 1, 'l': 1, 'y': 1})
```

### Accessing 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.

```python
from collections import Counter
letters = Counter("rooftop")
letters["r"]
1
letters["o"]
3
```

```python
for letter in letters:
	print(letter, letters[letter])
r 1
o3
f 1
t 1
p 1
```

Here’s what happens when the method `.keys()` is used:

```python
for letter in letters.keys():
	print(letter, letters[letter])
r 1
o3
f 1
t 1
p 1
```

Here’s an example with `.values()`:

```python
for count in letters.values():
	print(count)
1
3
1
1
1
```

Here’s the `.items()` method:

```python
for letter, count in letters.items():
	print(letter, count)
r 1
o3
f 1
t 1
p 1
```

### Deleting elements from `Counter`

If you want to delete an element from a counter in Python, you can use the `del` statement:

```python
from collections import Counter
example = {'b' : 1, 'l' : 1, 'u' : 1, 'e' : 1}
del example["b"]
print(Counter(example))
```

Your output will now look like this:

```python
Counter({'l' : 1, 'u' : 1, 'e' : 1})
```

### Excluding null values and negative values

You use the following code for Python `Counter` to remove null or negative values:

```python
from collections import Counter
values = Counter(a=6, b=0, c=1, d=-4)
values = +values
print(values)
```

The output for this is:

```python
Counter({'a' : 6, 'c' : 1})
```

### Determining 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 colours and track how many units of each colour are in stock. If a number is negative, it means the colour is out of stock but has already been preordered by a customer. To find out which colour has the most units available, we can use the following code:

```python
from collections import Counter
colour_variants = Counter({'blue' : 2, 'grey' : -1, 'black' : 0})
most_units = colour_variants.most_common(1)
print(most_units)
```

The output is:

```python
[('blue' : 2)]
```

To find out which colour has the fewest units, you can adjust the code by doing the following:

```python
from collections import Counter
colour_variants = Counter({'blue' : 2, 'grey' : -1, 'black' : 0})
fewest_units = colour_variants.most_common()[:-2:-1]
print(fewest_units)
```

This gives you:

```python
[('grey' : -1)]
```

### Sorting 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:

```python
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)
```

### Arithmetic 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:

```python
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)
```

```python
Counter({'a' : 6, 'b' : 3, 'c' : 3})
```

Subtraction:

```python
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)
```

```python
Counter({'a' : 2, 'b' : 1})
```

Since the value for c is negative, it isn’t included in the output.

Tip There’s lots more to learn about Python in our Digital Guide. For example, you can find articles on [installing Python](https://www.ionos.co.uk/digitalguide/websites/web-development/install-python/), [Python basics](https://www.ionos.co.uk/digitalguide/websites/web-development/python-tutorial/) and [Python operators](https://www.ionos.co.uk/digitalguide/websites/web-development/python-operators/).


This is a markdown version of: [https://www.ionos.co.uk/digitalguide/websites/web-development/python-counter/](https://www.ionos.co.uk/digitalguide/websites/web-development/python-counter/) for AI/LLM consumption.