2

Could you please explain me how and works in python? I know when

x y and 0 0 0 (returns x) 0 1 0 (x) 1 0 0 (y) 1 1 1 (y) 

In interpreter

>> lis = [1,2,3,4] >> 1 and 5 in lis 

output gives FALSE

but,

>>> 6 and 1 in lis 

output is TRUE

how does it work?

what to do in such case where in my program I have to enter if condition only when both the values are there in the list?

10
  • 3
    read it as 6 and (1 in lis) Commented Feb 9, 2016 at 9:56
  • 1
    Hint: what does just 1 and 5 print? How about 6 and 1? Commented Feb 9, 2016 at 9:57
  • if i use (6 and 1 ) in lis also it is TRUE how come it is supposed to be false right? Commented Feb 9, 2016 at 9:57
  • I think it is 6 and (1 in lis), not (6 and 1) in lis. Otherwise 0 and 1 in [0] would evaluate to true. Commented Feb 9, 2016 at 10:02
  • @khelwood It's not, see the link in my previous comment. Commented Feb 9, 2016 at 10:02

3 Answers 3

7

Despite lots of arguments to the contrary,

6 and 1 in lis 

means

6 and (1 in lis) 

It does not mean:

(6 and 1) in lis 

The page that Maroun Maroun linked to in his comments indicates that and has a lower precedence than in.

You can test it like this:

0 and 1 in [0] 

If this means (0 and 1) in [0] then it will evaluate to true, because 0 is in [0].

If it means 0 and (1 in [0]) then it will evaluate to 0, because 0 is false.

It evaluates to 0.

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

1 Comment

Even better, 0 and 0 in [0] returns 0, because and short-circuits if the first value is "not a true value".
2

This lines

lis = [1,2,3,4] 1 and 5 in lis 

are equivalent to

lis = [1,2,3,4] 1 and (5 in lis) 

Since bool(1) is True, it's like writing

lis = [1,2,3,4] True and (5 in lis) 

now since 5 is not in lis, we're getting True and False, which is False.

Comments

1

Your statement 1 and 5 in lis is evaluated as follows:

5 in lis --> false 1 and false --> false 

and 6 and 1 in lis is evaluated like this:

1 in lis --> true 6 and true --> true 

The last statement evaluates to true as any number other than 0 is true

In any case, this is the wrong approach to verify if multiple values exist ina list. You could use the all operator for this post:

all(x in lis for x in [1, 5]) 

3 Comments

@Jaco, thanks for the answer could you please explain how 6 and 1 returns 1 , x(which is 6) is false and y (which is 1) is true this should return x which is false right?
@sanyesh: 6 is true! Of numbers, only 0 is false. Check it with bool(6).
I am pretty sure it is 1 and (5 in lis), not (1 and 5) in lis.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.