[SciPy-User] Equality of lists and arrays

Robert Kern robert.kern at gmail.com
Sun Feb 13 23:16:41 EST 2011


On Sun, Feb 13, 2011 at 21:52, Dominique Orban
<dominique.orban at gmail.com> wrote:
> Hey there,
>
> I'm wondering if the following is intentional.
>
> 1< []==[0]  # Lists.
> 1> False
>
> 2< import numpy as np
> 3< a = np.array([]) ; b = np.array([0])
> 4< a==b     # Arrays.
> 4> array([], dtype=bool)

Everything up to here is certainly intended. The == operator
broadcasts, just like any other binary operator. Since the shape of b
is (1,), it will broadcast that array to be the same as a.shape:
namely (0,).

> 5< np.all(a==b)
> 5> True
>
> This is creating inconsistencies for me. If this behavior is
> intentional, what's the intended way to check for equality of arrays?

We implement np.all(x) as np.logical_and.reduce(x). The initial value
for the np.logical_and ufunc is True (just like the initial value for
np.multiply for is 1), so when given an empty array, you get that
initial value. This happens to coincide with regular Python's
treatment of all([]).

I suspect that you don't want the broadcasting behavior. Try this
function instead:

def really_equal(a, b):
    if a.shape != b.shape:
        return False
    return np.all(a == b)

If you are using this in unit tests, use
np.testing.assert_array_equal() instead.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the SciPy-User mailing list