9

What is better to use:

if var in X:
    #do_whatever
elif (var in Y):
    #do_whatever2

or:

if var in X:
    #do_whatever
if var in Y:
    #do_whatever2

Assuming var can't be in both X and Y... Is there any rule or common practice? Should I use elif? or a new if? or it doesn't matter??

EDIT: Great answers.. But can I say that if the first statement (#do_whatever) ends with a return or a break; where in its end the other condition will not be tested thus wasting the system resources or causing trouble, it's ok to do whatever.. I guess...

  • are you sure in the second part you din't mean else if...? – code shogan Aug 13 '11 at 18:21
16

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
| improve this answer | |
  • bar(5) returns 10, not 8 – Air Sep 6 '13 at 23:03
  • 1
    @AirThomas You are right, thanks! After such a long time you are the first one to spot it? nice ;) – Niklas R Sep 7 '13 at 17:41
5

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.

| improve this answer | |
2

If you need to perform both checks, you should use two separate ifs. If you want to check one or the order you should always use elif because

  • It's more efficient. You will save resources if your first condition is true.
  • You can have unexpected errors if both conditions are true.

Performance wise, you should also consider testing the most likely condition first.

| improve this answer | |
2

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.

| improve this answer | |
  • yes, it gets harder to maintain when commands are added if the code is expanded... – amyassin Aug 14 '11 at 23:56
1

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.

| improve this answer | |
  • 1
    No, but if Y is a very large list, then you'd be wasting resources by running a check that you know will always return false, if var in X is true. – João Silva Aug 13 '11 at 18:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.