[Python-ideas] Current use of addition in Python

Jonathan Fine jfine2358 at gmail.com
Mon Mar 4 13:41:38 EST 2019

First, I thank Rhodri for his question, and Eric for his reply (see
earlier messages in this thread).

I record the addition properties of collections.Counter and
numpy.array. Finally, some comments about len(), and a promise of more

Now for collections.Counter -- this is "provided to support convenient
and rapid tallies."

In my previous post, I noted that the built-in numeric types have the

Left and right cancellation
Existence of zero
Multiplication by a non-negative integer

Instances of Counter 'usually' have all of these properties, except
for multiplication by a non-negative integer. Here's an example where
cancellation fails
    >>> Counter(a=-1) + Counter()

Here's two more examples:
   >>> Counter(a=+1, b=-1) + Counter(a=-1, b=+1)
   >>> Counter(a=+1, b=-2) + Counter(a=-2, b=+1)
In the first example, it seems that the counters cancel. But the
second example shows that something else is going on.

Here's an example of associativity failing:
    >>> (Counter(a=+1) + Counter(a=-2)) + Counter(a=2)
    Counter({'a': 2})
    >>> Counter(a=+1) + (Counter(a=-2) + Counter(a=2))
    Counter({'a': 1})

The Python docs (URL above) notes that the Counter "methods are
designed only for use cases with positive values."


These arrays have all the properties listed above (commutative,
associative, left and right cancellation, multiplication by
non-negative integer), provided all the arrays have the same shape.
(The shape of an array is a tuple of non-negative integers.) And for
numpy.array, the zero must also have the same shape.

Briefly, a numpy array acts like a multi-dimensional vector. Here's an example:
    >>> array(range(3)), array(range(3, 6))
    (array([0, 1, 2]), array([3, 4, 5]))
    >>> array(range(3)) + array(range(3, 6))
    array([3, 5, 7])

Here's another example:
    >>> array(range(3, 6)) * 4
    array([12, 16, 20])
    >>> 4 * array(range(3, 6))
    array([12, 16, 20])

LENGTH -- len()

The numeric types don't have a length:
    >>> len(0)
    TypeError: object of type 'int' has no len()

The sequence and mapping types (such as list, tuple, str, bytes, set,
dict) are iterable, and have a length. Also, numpy.array and
collections.Counter have a length.

More on length tomorrow.


More information about the Python-ideas mailing list