Search code examples
pythontuplesboolean-operations

Using tuples instead of boolean operators


Is there a difference (in terms of performance, not readability) between the following ways of evaluating two (or more) conditions linked by and?

a == 1 and b == 2

or

(a,b) == (1,2)


The same for or:

a == 1 or b == 1

or

1 in (a,b)


Which way is preferable? The one using boolean operators or the other one using tuples?


Solution

  • Using and/or operators are almost always better in terms of performance (perhaps not for readability but that's another issue): 1. They avoid having to create tuple objects like you do in other examples which will be more costly in terms of space/time complexity 2. They short-circuit meaning there is a good chance you can avoid executing unnecessary portions of the code.