2

For example, I want, given the list given_list = [np.array([1,44,21,2])] Check if this list contains another numpy array, for example np.array([21,4,1,21])

I tried this but it checks if each element of the numpy array is the equal to the new numpy array

import numpy as np
given_list = [np.array([1,44,21,2])]
new_elem = np.array([21,4,1,21])

print([new_elem==elem for elem in given_list])

I would like to receive '[False]', but instead I get '[array([False, False, False, False])]'.

I don't understand why given_list is identified as a numpy array and not as a list of one numpy array.

2
  • numpy is too smart, if you have a == operator it will compare by elements. I just executed print(np.ones(4) == np.arange(4)) and it gives [False True False False] Commented Jul 26, 2022 at 13:01
  • You are iterating on given_list and comparing arrays. Nothing is treating the list as an array. Commented Jul 26, 2022 at 14:16

2 Answers 2

1

You can use numpy.array_equal:

[np.array_equal(new_elem, elem) for elem in given_list]

or numpy.allclose if you want to have some tolerance:

[np.allclose(new_elem, elem) for elem in given_list]

output: [False]

Sign up to request clarification or add additional context in comments.

Comments

1

If you are sure that your arrays have the same length you can do this task without cycling the elements of given_list. For example:

given_list = [np.array([1,44,21,2]), np.array([21,4,1,21])]
new_elem = np.array([21,4,1,21])

(np.array(given_list)==new_elem).all(axis=1) #array([False,  True])

Otherwise, you can use the @mozway 's [np.array_equal(new_elem, elem) for elem in given_list]

Comments

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.