How to check if all elements are in a tuple or list in another?

For example, I want to check that every element in the tuple (1, 2) is in tuple (1, 2, 3, 4, 5) . I don’t think using a loop is a good way to do this, I think it can be done on one line.

+5
source share
3 answers

You can use set.issubset or set.issuperset to verify that each item in one tuple or list is in another.

 >>> tuple1 = (1, 2) >>> tuple2 = (1, 2, 3, 4, 5) >>> set(tuple1).issubset(tuple2) True >>> set(tuple2).issuperset(tuple1) True 
+13
source

I think you want this: (Use all )

 >>> all(i in (1,2,3,4,5) for i in (1,6)) True 
0
source

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 just test them

 >>> tuple_containment ((1,2,3,4,5), (1,2)) True >>> tuple_containment ((1,2,3,4,5), (2,6)) False 
-1
source

Source: https://habr.com/ru/post/1239236/


All Articles