1

I am defining a function in Python that needs to check

if a==b:
  do.stuff()

In principle, a and b could be numpy arrays or integers, and I would like my implementation to be robust against this. However, to check equality for a numpy array, one needs to append the boolean with all(), which will break the code when a and b are integers.

Is there a simple way to code the equality test so that it works regardless of whether a and b are integers or numpy arrays?

3
  • Have you tried using type()? Commented Apr 2, 2021 at 0:32
  • 1
    Sticking all on the comparison isn't even correct for arrays - you'll get a variety of false positives and exceptions when the arrays have mismatched shapes. Commented Apr 2, 2021 at 0:36
  • 4
    (Despite the exception message telling you to use any or all, using any or all is very rarely the right move when you get one of those exceptions. Usually the right move is something like numpy.where or numpy.array_equal.) Commented Apr 2, 2021 at 0:37

1 Answer 1

1

how about this that works for both arrays and integers(numbers):

if np.array_equal(a,b):
    do.stuff()
Sign up to request clarification or add additional context in comments.

2 Comments

@mikefallopian glad it helped.
Mike, you might find it instructive to look at the code for array_equal. It starts by turning the inputs into arrays. That's a common step in numpy functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.