Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and operator works in python?

Tags:

python

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?

like image 320
sans0909 Avatar asked May 06 '26 03:05

sans0909


2 Answers

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.

like image 148
khelwood Avatar answered May 07 '26 17:05

khelwood


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.

like image 39
Maroun Avatar answered May 07 '26 16:05

Maroun