keyword 'in' not returning a bool?

L

Larry Bates

c said:
Try this

False

Why is this? Now try
True

Can someone explain what is going on?

Precedence. In:

't' in sample == True

sample == True is evaluated first
then 't' in that which is false

you should write

('t' in sample) == True

but that is unnecessary because

t' in sample

is easier to read and to code and less prone to this problem.

-Larry
 
R

Richard Brodie


It's comparison operator chaining:

't' in sample == True is like 't' == sample == True

and is equivalent to 't' in sample and sample == True
 
A

Arnaud Delobelle

Try this


False

Why is this?  Now try>>> bool('t' in sample) == True

True

Can someone explain what is going on?

This is because in Python '==' and 'in' are comparison operators and
in Python you can chain comparisons.

Typical usage is:

if 3 <= x < 9: # meaning (3 <= x) and (x < 9)
# do something...

So 't' in sample == True means the same as

('t' in sample) and (sample == True)

Which will never be true as sample is a dictionary.

To solve this, use brackets:
True

HTH
 
S

Sion Arrowsmith

False

Why is this?

http://docs.python.org/lib/comparisons.html

"Comparisons can be chained arbitrarily; for example, x < y <= z is
equivalent to x < y and y <= z, except that y is evaluated only once
[ ... ]
Two more operations with the same syntactic priority, "in" and "not
in", are supported only by sequence types"

So:
't' in sample == True
is equivalent to:
't' in sample and sample == True
and obviously:False
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top