lundi 3 février 2020

Python using if in List instead of or

I've been using python3 a lot for a class recently and figured out that you can write

if x in [1,2,3]:
    print("x is 1,2 or 3")

instead of

if x == 1 or x == 2 or x ==3:
    print("x is 1,2 or 3")

Is this considered good or bad practice, is it "pythonic" ?

Edit

The consensus seems to be that

if x in {1,2,3}: # set {}, not list []
    print("x is 1,2 or 3")

is more efficient, O(1) vs O(n), and therefore faster. Also, it expresses the same things less verbosely which makes it more "pythonic" as well.

Aucun commentaire:

Enregistrer un commentaire