Search code examples
pythonnumpyfunctionvectorequality

How do I check if two vectors are equal using a function?


I am attempting to check if two vectors are equal using a function. I don't know if I am using the correct function because I am not getting true or false as a return. Here is my code:

import numpy as np

x=np.array([1,2,3,4])

y=np.array([1,2,3,4])

def check(x,y):

    if x == y:
        print("They are equal")

When I run the code, it does not return anything so I am assuming it is not running the if statement. Am I writing the function correctly or what should I adjust?


Solution

  • To check the NumPy array equal you can use np.array_equal. And it's better to practice using return for function instead of printing the result.

    def check(x,y):
        if np.array_equal(x,y):
            return "They are equal"
        return "Not equal"
    

    Execution:

    print(check(x,y))
    # They are equal