lundi 6 juin 2016

Would it be better to use "if x in (y, z)" over "if x == y or x == z"?

Given this simple condition:

if x == y or x == z:
    print("Hello World!");

I understand that Python would first look to see if x is equal to y and if x is not equal to y it then it would check to see if x is equal to z, printing Hello World! if at least one of the conditions is True.

If I were to do this instead:

if x in (y, z):
    print("Hello World!");

To my understanding Python would iterate through the "yz" tuple and then print Hello World! if the value of x is in the "yz" tuple.

Which method would be faster / more efficient to use?
Would Python not bother to check if x was equal to z if x was equal to y?
Would Python still execute the code in the if statement if x was equal to y but not z?

Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire