I wanted to check if every element of one list or tuple is part of another one using Python. A set
has the issubset()
-method, but I couldn’t find anything build-in for a tuple. It was, however, rather quickly done:
>>> r = (1,2)
>>> l = (3,4,1,5,2)
>>> False not in [ e in l for e in r ]
True
>>> r = (1,9)
>>> False not in [ e in l for e in r ]
False
Why I’m posting this? I just found it cute code, somehow.
Comments
False not in ...
you should useall(e in l for e in r)
the buddies all(..) and any(..) are pretty neat for this.I did eventually use sets.
>>> set(range(3, 6)).issubset(range(10))
True
>>> set(range(3, 6)) <= range(10)
Traceback (most recent call last):
File “”, line 1, in
TypeError: can only compare to a set
>>> set(range(3, 6)) <= set(range(10))
True
> This is probably implied in Marius' response, but using a set brings the running time to O(m+n) rather than the O(m*n) found in your solution.
But building a Python set is rather more expensive than building a list (or even a bunch of lists). In the case this piece of code is in a tight loop and a hot spot, doing for the manual check can be less expensive.
That's after measuring naturally, the default should be set operations (though I'm not fond of using infix operators apart from & and |, I generally find the method calls much clearer)