Checking if List contains all items from another list
This video explains
Checking if List contains all items from another list
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Track title: CC B Schuberts Piano Sonata No 16 D
--
Chapters
00:00 Question
00:40 Accepted answer (Score 47)
00:55 Answer 2 (Score 8)
01:52 Answer 3 (Score 4)
02:09 Thank you
--
Full question
https://stackoverflow.com/questions/2856...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #algorithm
#avk47
Checking if List contains all items from another list
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Track title: CC B Schuberts Piano Sonata No 16 D
--
Chapters
00:00 Question
00:40 Accepted answer (Score 47)
00:55 Answer 2 (Score 8)
01:52 Answer 3 (Score 4)
02:09 Thank you
--
Full question
https://stackoverflow.com/questions/2856...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #algorithm
#avk47
ACCEPTED ANSWER
Score 50
You can use sets
t1 = [ (1,2), (3,4), (5,6), (7,8), (9,10), (11,12) ]
t2 = [ (3,4), (11,12) ]
set(t2).issubset(t1)
# returns true
# or equivalent use '<=' so
set(t2) <= set(t1)
# returns true
ANSWER 2
Score 9
For simplicity, you could do this:
print all(x in t1 for x in t2)
However, that's going to search through t1 for each element in t2. That probably doesn't matter when t1 is small as in this case, but to allow for larger collections I would do this:
s1 = set(t1)
print all(x in s1 for x in t2)
or this:
print set(t1).issuperset(t2)
This will generally be faster, since in is much faster for sets than for large lists. There's no major performance benefit in converting t2 to a set, regardless of size, so I wouldn't.
As always, it's better if you get your data in the "right" collection to begin with. So if the main purpose of t1 is to look things up in it, use a set in the first place rather than a list.
ANSWER 3
Score 4
You can create sets from those lists and use issubset method:
>>> t1 = [ (1,2), (3,4), (5,6), (7,8), (9,10), (11,12) ]
>>> t2 = [ (3,4), (11,12) ]
>>> s1 = set(t1)
>>> s2 = set(t2)
>>> s2.issubset(s1)
True