What is better to use:
if var in X:
#do_whatever
elif (var in Y):
#do_whatever2
or:
if var in X:
#do_whatever
i
If you need to perform both checks, you should use two separate if
s. If you want to check one or the order you should always use elif
because
Performance wise, you should also consider testing the most likely condition first.
Looking at the code without knowledge of the data then the elif case explicitely states your intentions and is to be preferred.
The two if statements case would also be harder to maintain as even if comments are added, they would still need to be checked.
If var
can't be in both X
and Y
, then you should use elif
. This way, if var in X
is true
, you don't need to pointlessly eval var in Y
.
If the second statement is impossible if the first one is true (as is the case here, since you said var can't be in both X and Y), then you should be using an elif. Otherwise, the second check will still run, which is a waste of system resources if you know it's going to false.
It makes a difference in some cases. See this example:
def foo(var):
if var == 5:
var = 6
elif var == 6:
var = 8
else:
var = 10
return var
def bar(var):
if var == 5:
var = 6
if var == 6:
var = 8
if var not in (5, 6):
var = 10
return var
print foo(5) # 6
print bar(5) # 10