keyword 'in' not returning a bool?

Arnaud Delobelle arnodel at googlemail.com
Fri Feb 8 12:33:49 EST 2008


On Feb 8, 5:09 pm, c james <cja... at callone.net> wrote:
> Try this
>
> >>> sample = {'t':True, 'f':False}
> >>> 't' in sample
> True
> >>> type('t' in sample)
> <type 'bool'>
> >>> 't' in sample == True
>
> 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:

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

HTH

--
Arnaud




More information about the Python-list mailing list