[Python-ideas] collections.Counter multiplication

MRAB python at mrabarnett.plus.com
Thu May 30 13:10:33 CEST 2013


On 30/05/2013 02:29, Steven D'Aprano wrote:
> On 30/05/13 10:52, Matthew Ruffalo wrote:
>> On 05/29/2013 08:06 PM, Steven D'Aprano wrote:
>>> On 30/05/13 06:17, James K wrote:
>>>> It should work like this
>>>>
>>>>      >>> from collections import Counter
>>>>      >>> Counter({'a': 1, 'b': 2}) * 2 # scalar
>>>>      Counter({'b': 4, 'a': 2})
>>>
>>> Under what circumstances would you do this?
>>>
>>> What is it about Counters that they should support multiplication when no other mapping type does?
>>
>> Counters are different from other mapping types because they provide a natural Python stdlib implementation of multisets -- the docs explicitly state that "The Counter class is similar to bags or multisets in other languages.". The class already has behavior that is different from other mapping types: Counter.__init__ can also take an iterable of hashable objects instead of another mapping, and Counter.update adds counts instead of replacing them.
>
>
> None of this answers my question. Under what circumstances would you multiply a counter by a scalar (let alone by another counter)? The fact that counters differ in some ways from other mappings doesn't justify every arbitrary change proposed.
>
Well, you can add Counters together:

 >>> from collections import Counter
 >>> Counter({'a': 1, 'b': 2}) + Counter({'a': 1, 'b': 2})
Counter({'b': 4, 'a': 2})

so multiplying by a non-negative scalar would have the same behaviour.

However, subtracting Counters won't return a negative value:

 >>> Counter({'a': 1, 'b': 2}) - Counter({'a': 1, 'b': 3})
Counter()

and NOT:

Counter({'b': -1})



More information about the Python-ideas mailing list