I often end up writing code like
if x == 1 or x == 5 or x == 10 or x == 22 :
pass
In English it seems redundant to keep repeating x, is there an easier or shorter way to write out an if-statement like that?
Maybe checking of existence of x's value in a tuple ( 1, 5, 10, 22, ) or something?
解决方案
Yes, you are right - either in a tuple or (if this check is made repeatedly) in a set.
So either do
if x in (1, 5, 10, 22):
pass
or, if you do this check often and the number of values is large enough,
myset = set((1, 5, 10, 22))
[...]
if x in myset:
pass
The myset stuff is the more useful, the more values you want to check. 4 values are quite few, so you can keep it simple. 400 values and you should use the set...
Another aspect, as pointed out by Marcin, is the necessary hashing for lookup in the set which may be more expensive than linearly searching a list or tuple for the wanted value.