I found, that there is related question, about how to find if at least one item exists in a list:
How to check if one of the following items is in a list?
But what is the best and pythonic way to find whether all items exists in a list?
Searching through the docs I found this solution:
>>> l = ['a', 'b', 'c']
>>> set(['a', 'b']) <= set(l)
True
>>> set(['a', 'x']) <= set(l)
False
Other solution would be this:
>>> l = ['a', 'b', 'c']
>>> all(x in l for x in ['a', 'b'])
True
>>> all(x in l for x in ['a', 'x'])
False
But here you must do more typing.
Is there any other solutions?
This is a different method:
Code:
I would probably use
set
in the following manner :or the other way round :
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 ...
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):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.What if your lists contain duplicates like this:
Sets do not contain duplicates. So, the following line returns True.
To count for duplicates, you can use the code:
So, the following line returns False.