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?

sans0909
  • 395
  • 7
  • 20

3 Answers3

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 2
    Even better, `0 and 0 in [0]` returns 0, because `and` short-circuits if the first value is "not a true value". – Vatine Feb 09 '16 at 10:37
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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
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])
Community
  • 1
  • 1
Alex
  • 21,273
  • 10
  • 61
  • 73