0

I've written this same kind of if statement line 20 or 30 times over the last few months, and I'm seeking a more efficient way to write it:

if type(_dt) == dt.date or type(_dt) == dt.datetime:

or more generally: if x = y, or x = z:

so I thought I'd try this in the interpreter:

In:    if 1 == 2 or 1:
        print('yay')

Out: yay

I was hoping someone could explain to me why this worked, and if this is the right way to do an inf statement like;

if x == y or z:

Thanks!

keynesiancross
  • 3,441
  • 15
  • 47
  • 87
  • In this case you could do `if type(_dt) in (dt.date, dt.datetime):` – Cory Kramer Sep 27 '22 at 12:25
  • Nice, I like that! any reason a tuple vs list? – keynesiancross Sep 27 '22 at 12:26
  • For the second part of the question check [Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?](https://stackoverflow.com/q/20002503/4046632) – buran Sep 27 '22 at 12:27
  • For tuple vs list, that will be basically the same so up to you. If the list got very long you could instead use a set which has faster containment check so like `{dt.date, dt.datetime}` but for only a few elements either tuple, set, or list will all act basically the same in terms of performance – Cory Kramer Sep 27 '22 at 12:28
  • 1
    It didn't work. It simply isn't an *error*, and it's behavior coincides with your expected behavior for *this* example. Try `0 == 1 or 0` instead. – chepner Sep 27 '22 at 12:30
  • Or the other way round: `0 == 1 or 2`. – Matthias Sep 27 '22 at 13:36

0 Answers0