Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of all counts in a collections.Counter

People also ask

How do you sum a count in python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

What is the use of collections Counter?

The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values. It allows you to count the items in an iterable list. Arithmetic operations like addition, subtraction, intersection, and union can be easily performed on a Counter.

What is collections Counter in Python?

Counter is an unordered collection where elements are stored as Dict keys and their count as dict value. Counter elements count can be positive, zero or negative integers. However there is no restriction on it's keys and values. Although values are intended to be numbers but we can store other objects too.

Can you add counters together python?

Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Note that if you want to save memory by modifying the Counter in-place rather than creating a new one, you can do a. update(b) or b. update(a) .


The code you have adds up the keys (i.e. the unique values in the list: 1+2+3+4+5+6=21).

To add up the counts, use:

In [4]: sum(Counter([1,2,3,4,5,1,2,1,6]).values())
Out[4]: 9

This idiom is mentioned in the documentation, under "Common patterns".


Sum the values:

sum(some_counter.values())

Demo:

>>> from collections import Counter
>>> c = Counter([1,2,3,4,5,1,2,1,6])
>>> sum(c.values())
9

Starting in Python 3.10, Counter is given a total() function which provides the sum of the counts:

from collections import Counter

Counter([1,2,3,4,5,1,2,1,6]).total()
# 9

sum(Counter([1,2,3,4,5,1,2,1,6]).values())