var match any of several values?

I can’t get this to work.

In a driver I need something to be True if var matches one of several values.

This works but is not very elegant or practical
1 if var==1 or var==3 or var==9 else 0

I want to distill this a bit but i can’t get this to work in any of the variations I’ve tried:
1 if var==[1, 3, 9] else 0

How should the syntax be to work here?

You can put the values in a list and then use ‘if a in b’ looks like this:


foo = [1,5,6,9]
bar = 5


if bar in foo:
    print('foobar')
else:
    print('no foobar')

1 if var in [1,3,9] else 0

Thank you Korchy! That did it.

Choose your structure according to what you’re doing with it.

Checking for membership inside a list is an O(n) operation, meaning that it slows down as the list grows. Obviously, if your item is the first in the list, you will receive the result almost instantly, but if it is at the end of the list, it’s far slower.

Sets / dicts are better for this, because they optimise lookups by storing hashes of the keys (or values, in case of sets). They aren’t sorted (or at least, not in Py 3.5), but they are used for when ordering doesn’t matter (in the case of sets), or when you want to associate a key with a value (dicts).

You can mimic a “switch” statement from C using dicts:


mapping = {'x': 'var was x', 'y': 'var was y', 'z': 'var was z'}
default_result = 'var wasn't handled'

var = 'x'
result = mapping.get(var, default_result)

Whereas sets are simply good for checking membership


if var in {'x', 'y', 'z'}:
    print("Var was x, y or z")
else:
    print("var was not x, y or z")