sans0909
sans0909

Reputation: 435

How and operator works in 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?

Upvotes: 2

Views: 107

Answers (3)

khelwood
khelwood

Reputation: 59096

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.

Upvotes: 7

Alex
Alex

Reputation: 21766

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])

Upvotes: 1

Maroun
Maroun

Reputation: 95948

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.

Upvotes: 2

Related Questions