Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 243
Page David Avatar asked Dec 26 '15 06:12

Page David


People also ask

How do you check if a tuple is in another tuple?

When it is required to check if one tuple is a subset of the other, the 'issubset' method is used. The 'issubset' method returns True if all the elements of the set are present in another set, wherein the other set would be passed as an argument to the method.

Can we compare a tuple and list in Python?

One of the most important differences between list and tuple is that list is mutable, whereas a tuple is immutable. This means that lists can be changed, and tuples cannot be changed.

How do you check if a tuple is in a list of tuples in Python?

When it is required to check if two list of tuples are identical, the '==' operator is used. The '==' operator checks to see if two iterables are equal or not.


2 Answers

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
like image 56
styvane Avatar answered Oct 10 '22 13:10

styvane


I think you want this: ( Use all )

>>> all(i in (1,2,3,4,5) for i in (1,2))
True 
like image 24
Ahsanul Haque Avatar answered Oct 10 '22 13:10

Ahsanul Haque