Suppose I want to check if a variable equals one of several values. Which of the following expressions should I use?
if s == 'one' or s == 'two' or s == 'three':
pass
if s in ('one', 'two', 'three'):
pass
if s in ['one', 'two', 'three']:
pass
if s in {'one', 'two', 'three'}:
pass
EDIT: From the answers / comments, I understood that:
- The first variant is least recommended, the others are considered equally "pythonic".
- The Performance differences in checking membership are negligible, for a short sequence. Tuples are least costly to create, sets require computing hashes.
- The four variants are not equivalent in some edge cases:
- The
in
operator checks for both identity and equality. - Logical
or
is short-circuited. I suspect that Membership tests of tuples and lists should be evaluated sequentially and thus be short-circuited, too. - Sets require hashable elements.
- The