Site icon Techolac – Computer Technology News

Python Count Items in List With the Help of Counter Objects

python count items in list

This articles shows the information regarding python count items in list. When we deal with data containers, such as tuples and lists, in Python we often require to count specific aspects. One common way to do this thing is to use the Python count Items In list () function– you specify the component you wants to count, and the functions returns the count.

Python Count Items in List With the Help of Counter Objects

In this articles, you can know about python count items in list here are the details below;

As you can see above, we used the Python count Items In list () function with a list of scores. Something to note: When the elements defined in the function aren’t included in the list, we’ll get a count of no, as expected. If we wish to count the occurrences of all the components, we’ll need to iterate them, as displayed in the following code snippet:

>>> print(‘*** Use the count() function with tuples’)
grades = (‘A’, ‘B’, ‘A’, ‘B’, ‘A’)
for grade in set(grades):
print(f’{grade} count: {grades.count(grade)})
print(‘*** Use the count() function with strings’)
word = ‘HelloHello’
for letter in set(word):
print(f’{letter} count: {word.count(letter)})
*** Use the count() function with tuples
B count: 2
A count: 3
*** Use the count() function with strings
e count: 2
o count: 2
l count: 4
H count: 2

Several things deserve highlighting in the above:

As shown above, we need to use a for loop to iterate the aspects to recover the counts for each private aspect. It’s a bit tiresome.

Is there another, the much better method to resolve the problem? If you understand Python, you need to think that the answer is yes. The Counters class is specifically designed to count aspects of these data structures.

The Counter Class– Overview

The Counters class is available through the collections module as part of Python’s basic library. As a subclass of the dict classes, it provides a couple of highly specialized methods that handle item counting. To create counter things, you can simply set an iterable to the Counter class instance manufacturer, as shown:

>>> from collections import Counter
letters = ‘abcabcdaabb’
letter_counter = Counter(letters)
print(“Letter Counter:”, letter_counter)
Letter Counter: Counter({‘a’: 4, ‘b’: 4, ‘c’: 2, ‘d’: 1})

As you can see inline 7, a Counter thing looks like a dictionary with a series of key-value sets. Specifically, the secrets are the counted aspects, while the worths are the counters for the matching keys. If you wish to recover the counts for private products, you can do that just as you deal with a dictionary. Some insignificant examples are shown listed below. Especially if the key does not exist in the Counter things, the count will be no.

>>> letter_counter[‘a’]
>>> letter_counter[‘c’]
>>> letter_counter[‘z’]

One vital thing to note is that because of the key-value mapping system, just hashable things can be tracked by Counter things. In Python Count Items In List, immutable objects, such is strings, integers, tuples are all the hashable, while mutable things, such as lists, sets, and dictionaries, are un-hashable. A detailed discussion of object hash ability is beyond the scope of the present article, and if you’re interested, you can find more info in my previous short article on this subject.

The following code shows you an insignificant example when we try to use Counter with unhashable items– lists. The mistake message plainly informs us that Python cannot instantiate a Counter item for us because lists are unhashable things in Python.

>>> nested_lists = [[1, 2, 3], [0, 1, 2], [2, 3, 4]]
unhashable_counter = Counter(nested_lists)
Traceback (most recent call last):
# remove some extra lines for clarity
TypeError: unhashable type: ‘list’

Determine one of the most Frequent Items

Typically, we need to understand what the frequently taking place items in a data container (e.g., lists and tuples) are. Before we see the option with the Counter things, let’s see how to achieve this functionality using some tedious code:

>>> letters = ‘xxxxx_yyyy_zzz_aaaaaa_bbbbbb_c’
# Use dictionary comprehension to count each member
letter_counts = {x: letters.count(x) for x in set(letters)}
letter, count = max(letter_counts.items(), key=lambda x: x[1])
print(f”The most frequent letter is {letter} with a count of {count}.”)
The most frequent letter is b with a count of 6.

As revealed above, we first needed to utilize the list’s Python count Items In list () approach to count each of the special products in the list and save the counting result to a dictionary. Next, we needed to utilize the integrated max() function to sort the products of the dictionary by specifying the sorting secret to use the worth of each key-value pair. Certainly, this way works; however, it’s not the idiomatic way, in which case, we must think about using Counter.

>>> letter_counter = Counter(letters)
most_freq_letter = letter_counter.most_common(1)
print(“Most frequent:”, most_freq_letter)
Most frequent: [(‘a’, 6)]

As revealed above, the impression that you must have is how succinct the code is compared to the non-idiomatic execution of this functionality. It’s all since the Counter things has a helpful most_common() approach, which quickly pulls the needed details for us– the most often occurring item and its associated count. In fact, to provide us more versatility, we have the option to learn an approximate variety of the most often taking place items, as shown listed below.

>>> # To find out the most frequent 2 letters
print(“Most frequent 2 letters:”, letter_counter.most_common(2))
Most frequent 2 letters: [(‘a’, 6), (‘b’, 6)]
>>> # To find out the most frequent 3 letters
print(“Most frequent 3 letters:”, letter_counter.most_common(3))
Most frequent 3 letters: [(‘a’, 6), (‘b’, 6), (‘x’, 5)]

Please notes that when you don’t specify any numbers in the most_common() technique, all the components will be returned as a list in the coming down the order of the counts. This descending order can be extremely beneficial, which allows us to recover the item with the least count, as revealed below.

>>> # To find out the least frequent letter
print(“Least frequent letter:”, letter_counter.most_common()[1])
Least frequent letter: (‘c’, 1)

Update the Counter Object

Formerly, we saw that the Counter things are utilized to count the aspects in a list. But what if we gets another list and wish to upgrade the initial Counter things without developing a new one?

One possible solution is to benefit from Counter things, carrying out the mapping procedure such that we can update each secret’s worth appropriately. Especially, if the secret doesn’t exist in the initial Counter item, unlike the integrated dict information type, a KeyValue exception won’t be raised, since by default, a missing out on key in a Counter object has a worth of 0, as we saw with accessing specific products.

>>> letters0 = ‘xxxxx_yyyy_zzz_aaaaaa_bbbbbb_c’
letter_counter = Counter(letters0)
print(“** Before updating:”, letter_counter)
letters1 = list(‘ddd_llllll’)
for letter in letters1:
letter_counter[letter] += 1
print(“** After updating:”, letter_counter)
** Before updating: Counter({‘a’: 6, ‘b’: 6, ‘x’: 5, ‘_’: 5, ‘y’: 4, ‘z’: 3, ‘c’: 1})
** After updating: Counter({‘_’: 6, ‘a’: 6, ‘b’: 6, ‘l’: 6, ‘x’: 5, ‘y’: 4, ‘z’: 3, ‘d’: 3, ‘c’: 1})

There’s a more elegant way to updates the initial Counter item– utilize the Counter’s update() technique. Don’t puzzle this update() approach with the dict’s upgrade() technique, which updates the values of matching secrets. Rather, the Counter’s update() technique will internally generate the counts for the products and utilize these counts to upgrade the initial Counter item, as displayed in the code snippet listed below.

>>> letters2 = “aaaaa_bbbbbbbb”
print(“Letter Counter:”, letter_counter)
Letter Counter: Counter({‘b’: 14, ‘a’: 11, ‘_’: 7, ‘l’: 6, ‘x’: 5, ‘y’: 4, ‘z’: 3, ‘d’: 3, ‘c’: 1})

Mathematical Operations

The name of the Counter class is informative, which informs you thats it counts for us. As we have seen, we can update the counts with the update() technique. More broadly, when we have several Counter things, we can have addition and subtraction operations with them. When we add Counter items, the counts for the components are combined.

The following code reveals you such operation, which should be obvious:

>>> abc = “aaabbbccc”
amz = “aaaammmmzzzz”
abc_Counter = Counter(abc)
amz_Counter = Counter(amz)
print(“abc_Counter:”, abc_Counter)
print(“amz_Counter:”, amz_Counter)
abc_Counter: Counter({‘a’: 3, ‘b’: 3, ‘c’: 3})
amz_Counter: Counter({‘a’: 4, ‘m’: 4, ‘z’: 4})
>>> abc_Counter + amz_Counter
Counter({‘a’: 7, ‘m’: 4, ‘z’: 4, ‘b’: 3, ‘c’: 3})

In a comparable style, we can deduct one Counter item from another Counter thing using the minus operator, as revealed below.

>>> abc_Counter amz_Counter
Counter({‘b’: 3, ‘c’: 3})

Subtraction of Counter Objects

In the above code, something to note is that when we use the subtraction operator, the resulting Counter object will just consist of those key-value pairs with positive counts. This habits is different from Counter’s approach subtract(), which will likewise consist of negative counts. Likewise, as noted previously, when a Counter does not consist of the components, they have a count of zero by default. With these two things in mind, let’s see how the deduct() approach works with Counter things.

>>> print(“** Before subtraction:”, abc_Counter)
print(“** After subtraction:”, abc_Counter)
** Before subtraction: Counter({‘a’: 3, ‘b’: 3, ‘c’: 3})
** After subtraction: Counter({‘b’: 3, ‘c’: 3, ‘a’: 1, ‘m’: 4, ‘z’: 4})

As you can see, the resulting Counter item includes a number of elements with negative counts. Another thing to note is that the subtract() technique changes the counts in-place, which indicates that the deduct() method returns None, and it alters the original Counter things, counts.

Set-Like Operations

In addition to the assistance of mathematical operations, there are two set-like operations offered to the Counter things: union and crossway. To produce a “union” Python count Items In list of two Counter items, you just utilize the OR operator (i.e., the vertical bar) to link them. The union operation will be carried out by using the optimum counts of each matching type in the resulting Counter things. A minor example is shown below:

>>> abc_counter = Counter(‘aabbcc’)
acd_counter = Counter(‘aaaacdddd’)
print(“Union of Counters:”, abc_counter | acd_counter)
Union of Counters: Counter({‘a’: 4, ‘d’: 4, ‘b’: 2, ‘c’: 2})

To produce an “intersection” of 2 Counter things, you’ll merely utilize the AND operator (i.e., the & indication) to link them. The crossway operation will be carried out by using the minimal counts of each matching key in the resulting Counter object. A minor example is shown listed below.

>>> print(“abc_counter:”, abc_counter)
print(“acd_counter:”, acd_counter)
print(“Intersection of Counters:”, abc_counter & acd_counter)
abc_counter: Counter({‘a’: 2, ‘b’: 2, ‘c’: 2})
acd_counter: Counter({‘a’: 4, ‘d’: 4, ‘c’: 1})
Intersection of Counters: Counter({‘a’: 2, ‘c’: 1})

Highlights of Other Features

In the previous areas, we discovered that we could develop Counter things from iterables, including tuples, lists, and strings. As pointed out formerly, the Counter class is a subclass of the built-in dict class, so we can use instantiation approaches that are offered to the dict class. Some examples are shown listed below with accompanying explanatory comments:

>>> # Create Counter from a mapping
Counter({“a”: 5, “b”: 4, “c”: 3})
Counter({‘a’: 5, ‘b’: 4, ‘c’: 3})
>>> # Create Counter from keyword arguments
Counter(x=1, y=2, z=3)
Counter({‘z’: 3, ‘y’: 2, ‘x’: 1})

We’ve seen that the counts of the Counter items are stemmed from counting or mathematical operations. We can directly set the count of particular elements if it’s a suitable use. In addition, we can get rid of the components from the Counter object, much like removing a key-value set from a direct object. See below for such uses:

>>> letter_counts = Counter(‘abbcccdddd’)
print(“Current Count:”, letter_counts)
Current Count: Counter({‘d’: 4, ‘c’: 3, ‘b’: 2, ‘a’: 1})
>>> # Update the a’s count
letter_counts[‘a’] = 10
print(“After changing:”, letter_counts)
After changing: Counter({‘a’: 10, ‘d’: 4, ‘c’: 3, ‘b’: 2})
>>> # Remove the b’s count
del letter_counts[‘b’]
print(“After removing:”, letter_counts)
After removing: Counter({‘a’: 10, ‘d’: 4, ‘c’: 3})

Another useful technique of Counter things is the aspects() approach, which develops an iterator of all items with each having the wanted occurrences matching its count. This approach is especially handy for iterating different items of known numbers.

>>> # Use the elements() method to get the items with specific counts
item_counter = Counter(a=1, b=2, c=3, x=4, y=5, z=6)


In this post, we examined the interesting Counter class for counting hashable objects in sequences, consisting of tuples, lists, and strings. As a subclass of the dict data type, we can develop Counter things from the sequences in addition to mapping and keyword arguments, just as regular diet items. The Counter object is highly versatile because you can manipulate the counts of these components as you desire. You can even update, merge, and intersect Counter objects.

The majority of remarkably, it has the most Python count Items In list () method, which permits us to discover the most frequent items with one line of code. It’s likewise possible to learn the least regular items by taking advantage of the most_common() technique, which sorts the products in coming down the order, permitting us to recover the last item for the least common product.

You can check over other articles like:

Exit mobile version