yingnan liu
yingnan liu

Reputation: 509

Python IF multiple "and" "or" in one statement

I am just wondering if this following if statement works:

    value=[1,2,3,4,5,f]
    target = [1,2,3,4,5,6,f]
    if value[0] in target OR value[1] in target AND value[6] in target:
       print ("good")

My goal is to make sure the following 2 requirements are all met at the same time: 1. value[6] must be in target 2. either value[0] or value[1] in target Apologize if I made a bad example but my question is that if I could make three AND & OR in one statement? Many thanks!

Upvotes: 9

Views: 57161

Answers (2)

Javi
Javi

Reputation: 1211

If I am not wrong and has priority, so doing:

if x==True or y==True and z==True:
    do smth

would be like doing:

if x==True or (y==True and z==True):

not like doing:

(if x==True or y==True) and z==True:

But as @alecxe commented, it is always safer to use () when more than 2 logic arguments are used.

Upvotes: 0

alecxe
alecxe

Reputation: 473893

Use parenthesis to group the conditions:

if value[6] in target and (value[0] in target or value[1] in target):

Note that you can make the in lookups in constant time if you would define the target as a set:

target = {1,2,3,4,5,6,f}

And, as mentioned by @Pramod in comments, in this case value[6] would result in an IndexError since there are only 6 elements defined in value and indexing is 0-based.

Upvotes: 17

Related Questions