How To Check If All Elements In A Tuple Or List Are In Another?
For example, I want to check every elements in tuple (1, 2) are in tuple (1, 2, 3, 4, 5). I don't think use loop is a good way to do it, I think it could be done in one line.
Solution 1:
You can use set.issubset
or set.issuperset
to check if every element in one tuple or list is in other.
>>> tuple1 = (1, 2)
>>> tuple2 = (1, 2, 3, 4, 5)
>>> set(tuple1).issubset(tuple2)
True
>>> set(tuple2).issuperset(tuple1)
True
Solution 2:
I think you want this: ( Use all )
>>> all(i in (1,2,3,4,5) for i in (1,2))
True
Solution 3:
Another alternative would be to create a simple function when the set doesn't come to mind.
def tuple_containment(a,b):
ans = True
for i in iter(b):
ans &= i in a
return ans
Now simply test them
>>> tuple_containment ((1,2,3,4,5), (1,2))
True
>>> tuple_containment ((1,2,3,4,5), (2,6))
False
Post a Comment for "How To Check If All Elements In A Tuple Or List Are In Another?"