neox
neox

Reputation: 81

How do I sum many Counter objects in Python?

If I use Pythons sum function, I get an "unsupported operand type(s)" error, though adding c1 = Counter(..), c2 = Counter(..) like this: c1+c2 works.

Upvotes: 1

Views: 490

Answers (1)

Eric
Eric

Reputation: 97591

Always read the full error:

TypeError: unsupported operand type(s) for +: 'int' and 'Counter'

sum takes a starting value to sum from, which by default is the integer 0. You need to specify a starting value of type Counter, such as the empty counter:

sum([c1, c2, c3], Counter())

Or alternatively, spell it:

reduce(operator.add, [c1, c2, c3])

Upvotes: 4

Related Questions