Thomas Kühn
Thomas Kühn

Reputation: 9830

Most concise way to check if multiple variables are between the same limits

Let's say I have three variables, x, y, and z, and I want to perform a check whether all three of them are inside the limits A and B. I'm looking for the most concise and pythonic way to do so. I know that I can check one variable as

if A < x < B:
   [some code here]

However, for three variables the shortest I could come up with without the help of something like numpy is

if (A < x < B) and (A < y < B) and (A < z < B):
   [some code here]

Is there any better way to do this?

Upvotes: 1

Views: 121

Answers (2)

BarricadeX75
BarricadeX75

Reputation: 106

Try using all().

e.g.

if all(A < n < B for n in (x, y, z)):
    ...

Upvotes: 1

Sociopath
Sociopath

Reputation: 13426

store them and list and use all

lst = [x,y,z]

if all(A<i<B for i in lst):
    # your code
    # print(True)

Upvotes: 2

Related Questions