Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: See if one set contains another entirely?

Tags:

python

set

Is there a fast way to check if one set entirely contains another?

Something like:

>>>[1, 2, 3].containsAll([2, 1]) True  >>>[1, 2, 3].containsAll([3, 5, 9]) False 
like image 880
Nick Heiner Avatar asked May 04 '10 13:05

Nick Heiner


2 Answers

Those are lists, but if you really mean sets you can use the issubset method.

>>> s = set([1,2,3]) >>> t = set([1,2]) >>> t.issubset(s) True >>> s.issuperset(t) True 

For a list, you will not be able to do better than checking each element.

like image 188
danben Avatar answered Sep 17 '22 10:09

danben


For completeness: this is equivalent to issubset (although arguably a bit less explicit/readable):

>>> set([1,2,3]) >= set([2,1]) True >>> set([1,2,3]) >= set([3,5,9]) False 
like image 22
ChristopheD Avatar answered Sep 17 '22 10:09

ChristopheD