Noe Nieto Noe Nieto - 4 years ago 164
Python Question

Can Python test the membership of multiple values in a list?

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?

Answer Source

This does what you want:

>>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
True

Your result happens because python interprets your expression as a tuple:

>>> 'a', 'b'
('a', 'b')
>>> 'a', 5 + 2
('a', 7)
>>> 'a', 'x' in 'xerxes'
('a', True)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download