I want to test if two or more values have membership on a list, but I'm getting an unexpected result:
>>> 'a','b' in ['b', 'a', 'foo', 'bar']
('a', True)
So, Can Python test the membership of multiple values at once in a list? What does that result mean?
This question is related to
python
I would say we can even leave those square brackets out.
array = ['b', 'a', 'foo', 'bar']
all([i in array for i in 'a', 'b'])
Both of the answers presented here will not handle repeated elements. For example, if you are testing whether [1,2,2] is a sublist of [1,2,3,4], both will return True. That may be what you mean to do, but I just wanted to clarify. If you want to return false for [1,2,2] in [1,2,3,4], you would need to sort both lists and check each item with a moving index on each list. Just a slightly more complicated for loop.
If you want to check all of your input matches,
>>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
if you want to check at least one match,
>>> any(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
[x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]
The reason I think this is better than the chosen answer is that you really don't need to call the 'all()' function. Empty list evaluates to False in IF statements, non-empty list evaluates to True.
if [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]:
...Do something...
Example:
>>> [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]
['a', 'b']
>>> [x for x in ['G','F'] if x in ['b', 'a', 'foo', 'bar']]
[]
Another way to do it:
>>> set(['a','b']).issubset( ['b','a','foo','bar'] )
True
how can you be pythonic without lambdas! .. not to be taken seriously .. but this way works too:
orig_array = [ ..... ]
test_array = [ ... ]
filter(lambda x:x in test_array, orig_array) == test_array
leave out the end part if you want to test if any of the values are in the array:
filter(lambda x:x in test_array, orig_array)
Here's how I did it:
A = ['a','b','c']
B = ['c']
logic = [(x in B) for x in A]
if True in logic:
do something
I'm pretty sure in
is having higher precedence than ,
so your statement is being interpreted as 'a', ('b' in ['b' ...])
, which then evaluates to 'a', True
since 'b'
is in the array.
See previous answer for how to do what you want.
The Python parser evaluated that statement as a tuple, where the first value was 'a'
, and the second value is the expression 'b' in ['b', 'a', 'foo', 'bar']
(which evaluates to True
).
You can write a simple function do do what you want, though:
def all_in(candidates, sequence):
for element in candidates:
if element not in sequence:
return False
return True
And call it like:
>>> all_in(('a', 'b'), ['b', 'a', 'foo', 'bar'])
True
Source: Stackoverflow.com