What is the best way to check if an array/tuple/list only contains elements in another array/tuple/list?
I tried the following 2 approaches, which is better/more pythonic for the different kinds of collections?
What other (better) methods can I use for this check?
import numpy as np
input = np.array([0, 1, -1, 0, 1, 0, 0, 1])
bits = np.array([0, 1, -1])
# Using numpy
a=np.concatenate([np.where(input==bit)[0] for bit in bits])
if len(a)==len(input):
print 'Valid input'
# Using sets
if not set(input)-set(bits):
print 'Valid input'
Your
# Using numpyone is awfully inefficient for large sets in that it creates an entire copy of your input list.I’d probably do:
That’s an extremely pythonic way to write what you’re trying to do, and it has the benefit that it won’t create an entire
list(orset) that might be large, and it’ll stop (and returnFalse) the first time it encounters an element frominputthat’s not inbits.