How to compare multiple variables to the same value?

Question:

I am using Python and I would like to have an if statement with many variables in it.

Such as:

if A, B, C, and D >= 2:
    print (A, B, C, and D)

I realize that this is not the correct syntax and that is exactly the question I am asking — what is the correct Python syntax for this type of an if statement?

Asked By: chingchong

||

Answers:

How about:

if A >= 2 and B >= 2 and C >= 2 and D >= 2:
    print A, B, C, D

For the general case, there isn’t a shorter way for indicating that the same condition must be true for all variables – unless you’re willing to put the variables in a list, for that take a look at some of the other answers.

Answered By: Óscar López

Except that she’s probably asking for this:

if A >= 2 and B >= 2 and C >= 2 and D >= 2:
Answered By: Dan

Another idea:

if min(A, B, C, D) >= 2:
    print A, B, C, D
Answered By: Fred Larson

Depending on what you are trying to accomplish, passing a list to a function may work.

def foo(lst):
    for i in lst:
        if i < 2:
            return
    print lst
Answered By: Phil

I’d probably write this as

v = A, B, C, D
if all(i >= 2 for i in v):
    print v
Answered By: DSM

You want to test a condition for all the variables:

if all(x >= 2 for x in (A, B, C, D)):
    print(A, B, C, D)

This should be helpful if you’re testing a long list of variables with the same condition.


If you needed to check:

if A, B, C, or D >= 2:

Then you want to test a condition for any of the variables:

if any(x >= 2 for x in (A, B, C, D)):
    print(A, B, C, D)
Answered By: Limbo Peng

If you have ten variables that you are treating as a group like this, you probably want to make them elements of a list, or values in a dictionary, or attributes of an object. For example:

my_dict = {'A': 1, 'B': 2, 'C': 3 }

if all(x > 2 for x in my_dict.values()):
    print "They're all more than two!"
Answered By: Ned Batchelder
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.