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.
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.
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With