[Python-ideas] collections.Counter should implement __mul__, __rmul__

Peter Norvig peter at norvig.com
Sun Apr 15 17:05:04 EDT 2018


For most types that implement __add__, `x + x` is equal to `2 * x`.

That is true for all numbers, list, tuple, str, timedelta, etc. -- but not
for collections.Counter. I can add two Counters, but I can't multiply one
by a scalar. That seems like an oversight.

It would be worthwhile to implement multiplication because, among other
reasons, Counters are a nice representation for discrete probability
distributions, for which multiplication is an even more fundamental
operation than addition.

Here's an implementation:

    def __mul__(self, scalar):
        "Multiply each entry by a scalar."
        result = Counter()
        for key in self:
            result[key] = self[key] * scalar
        return result

    def __rmul__(self, scalar):
        "Multiply each entry by a scalar."
        result = Counter()
        for key in self:
            result[key] = scalar * self[key]
        return result
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180415/af6e24e2/attachment.html>


More information about the Python-ideas mailing list