How to check if all of the following items are in a list?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Question
00:49 Accepted answer (Score 273)
01:25 Answer 2 (Score 72)
01:56 Answer 3 (Score 22)
02:20 Answer 4 (Score 12)
02:59 Thank you
--
Full question
https://stackoverflow.com/questions/3931...
Question links:
[How to check if one of the following items is in a list?]: https://stackoverflow.com/questions/7402...
Answer 1 links:
[set]: http://rgruet.free.fr/PQR26/PQR2.6.html#...
Answer 2 links:
[backported]: https://docs.python.org/dev/whatsnew/2.7...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#list #python #inclusion
#avk47
ACCEPTED ANSWER
Score 302
Operators like <= in Python are generally not overriden to mean something significantly different than "less than or equal to". It's unusual for the standard library does this--it smells like legacy API to me.
Use the equivalent and more clearly-named method, set.issubset. Note that you don't need to convert the argument to a set; it'll do that for you if needed.
set(['a', 'b']).issubset(['a', 'b', 'c'])
ANSWER 2
Score 73
I would probably use set in the following manner :
set(l).issuperset(set(['a','b']))
or the other way round :
set(['a','b']).issubset(set(l))
I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/intersection/differences between collections, but it may not be the best option in this situation ...
ANSWER 3
Score 25
I like these two because they seem the most logical, the latter being shorter and probably fastest (shown here using set literal syntax which has been backported to Python 2.7):
all(x in {'a', 'b', 'c'} for x in ['a', 'b'])
# or
{'a', 'b'}.issubset({'a', 'b', 'c'})
ANSWER 4
Score 14
What if your lists contain duplicates like this:
v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']
Sets do not contain duplicates. So, the following line returns True.
set(v2).issubset(v1)
To count for duplicates, you can use the code:
v1 = sorted(v1)
v2 = sorted(v2)
def is_subseq(v2, v1):
"""Check whether v2 is a subsequence of v1."""
it = iter(v1)
return all(c in it for c in v2)
So, the following line returns False.
is_subseq(v2, v1)