Search code examples
arrayspython-3.xnumpysequencemembership

How to check if a numpy array is inside a Python sequence?


I'd like to check if a given array is inside a regular Python sequence (list, tuple, etc). For example, consider the following code:

import numpy as np

xs = np.array([1, 2, 3])
ys = np.array([4, 5, 6])

myseq = (xs, 1, True, ys, 'hello')

I would expect that simple membership checking with in would work, e.g.:

>>> xs in myseq
True

But apparently it fails if the element I'm trying to find isn't at the first position of myseq, e.g.:

>>> ys in myseq
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

So how can I perform this check?

If possible I'd like to do this without having to cast myseq into a numpy array or any other sort of data structure.


Solution

  • You can use any with the test that is appropriate:

    import numpy as np
    
    xs = np.array([1, 2, 3])
    ys = np.array([4, 5, 6])
    zs = np.array([7, 8, 9])
    
    myseq = (xs, 1, True, ys, 'hello')
    
    def arr_in_seq(arr, seq):
        tp=type(arr)
        return any(isinstance(e, tp) and np.array_equiv(e, arr) for e in seq)
    

    Testing:

    for x in (xs,ys,zs):
        print(arr_in_seq(x,myseq))
    True
    True
    False