1

I want to know if a list [a, b] is present in numpy ndarray.

I tried this :

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

[1, 5] in list1

The result is :

True

It seems that it only the presence of the first number is checked, leading to a false response.

What is the good way to check if the list is present or not ?

Mairkur
  • 177
  • 1
  • 15
  • Possible duplicate of [testing whether a Numpy array contains a given row](https://stackoverflow.com/questions/14766194/testing-whether-a-numpy-array-contains-a-given-row) – jsmolka Mar 02 '18 at 12:06

2 Answers2

3

This is one way:

import numpy as np

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

lst = np.array([1, 5])
any((lst==i).all() for i in arr)  # False

lst = np.array([1, 2])
any((lst==i).all() for i in arr)  # True
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Thanks for the answer. It works well. Why did you convert the second list (lst) to a np array ? – Mairkur Mar 02 '18 at 12:11
  • @Mairkur, you should compare similar types, e.g. list to list or np.array to np.array. The conversion ensures this happens. – jpp Mar 03 '18 at 18:38
0

A simple way is to use tolist().

>>> list1 = np.array([[1, 2], [1, 3], [2, 4]])
>>> [1, 2] in list1.tolist()
True
>>> [1, 5] in list1.tolist()
False
Austin
  • 25,759
  • 4
  • 25
  • 48