# Checking a one-dimensional numpy array in a multidimensional array without a loop

Input

array([[10, 11, 12, 13, 26, 28, 11],
[ 4,  9, 19, 20, 21, 26, 12],
[ 1,  7, 10, 23, 28, 32, 16],
[ 4,  6,  7, 10, 13, 25,  3],
[ 4,  6, 15, 17, 30, 31, 16]])

test = np.array([10, 11, 12, 13, 26, 28, 11])


Trying

def check(test,array):
for i in array:
if np.array_equal(i,test):
print('in')
break
print('not in')


Is there any simple method without using for...in...if...else structure?

• I thought that, but then I checked it and it doesn't work for numpy arrays. May 7 '18 at 12:56
• i, obviously, didn't take my pills this morning. sorry May 7 '18 at 15:13

There are indeed ways. The most pythonic one is probably to use a generator comprehension.

def check(test,array):
return any(numpy.array_equal(x, test) for x in array)


Note that this is not quite the same behaviour as it returns a Boolean rather than printing the result, but that behaviour should be easy enough to add outside.

As an aside, I don't like the variable name test. It sounds to me like the name of a predicate function rather than the name of an array you want to look for.

The name check is also rather too general to usefully say what it is checking.

Now I'm perhaps overly fond of slightly too descriptive names, but I'd probably be calling this def is_row_in_array(row, array):

• What about any(map(lambda x:np.array_equal(x,test), array)) ? Is it more pythonic?
– Jack
May 7 '18 at 14:12
• That's controversial. As near as I can tell the trend is slightly to prefer comprehensions, and in particular to prefer comprehensions when you would otherwise have to define a lambda. Performance concerens also prefer comprehensions to map with a lambda. Of course some people, including myself, do find map more natural to think in. I actually wrote the map version in this answer before translating it to a generator comprehension! May 7 '18 at 14:38
• For a bit of history about just how controversial, Guido van Rossum, the original creator of Python tried to drop map, filter and lambda from Python 3! artima.com/weblogs/viewpost.jsp?thread=98196 May 7 '18 at 14:57

If you don't like the looping and the if ... statements you could use solely NumPy methods:

def is_row_in_array(row , arr):
return np.any(np.sum(np.abs(arr-row), axis=1) == 0)

• (arr == row).all(axis=1).any() is shorter and a bit faster, but the general approach in this answer is right. May 8 '18 at 13:46
• @Gareth Rees, nice improvement. May 8 '18 at 15:52