9

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!

4
  • You will index error when you will try to access value[6] and apart of that, what is f in value list, is that some variable or element of list, if this is the element of list, then you should enclose it under single or double quote. Commented Mar 30, 2016 at 1:54
  • What course materials are you using that instruct you to use AND and OR in uppercase? Commented Mar 30, 2016 at 1:57
  • @Pramod got it! thx! Commented Mar 30, 2016 at 2:07
  • 1
    @TigerhawkT3 actually i put them in uppercase cuz it helps ppl quickly understand what my question is. nothing to do with ANY course materials Commented Mar 30, 2016 at 2:10

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.