Logic operators with "in" statement

Mr.SpOOn mr.spoon21 at gmail.com
Mon Nov 16 15:02:28 CET 2009


Hi,
I'm trying to use logical operators (or, and) with the "in" statement,
but I'm having some problems to understand their behavior.

In [1]: l = ['3', 'no3', 'b3']

In [2]: '3' in l
Out[2]: True

In [3]: '3' and '4' in l
Out[3]: False

In [4]: '3' and 'no3' in l
Out[4]: True

This seems to work as I expected.
------------

In [5]: '3' and 'no3' or '3' and '4' in l
Out[5]: 'no3'

In [6]: ('3' and 'no3') or ('3' and '4') in l
Out[6]: 'no3'

I don't understand these outputs.
---------------

In [7]: (('3' and 'no3') or ('3' and '4')) in l
Out[7]: True

In [10]: (('b3' and '4') or ('3' and 'no3')) in l
Out[10]: False

Here I expected to get True in the second case too, so clearly I don't
really get how they work.

Can you help me?
What I really need is to create a sequence of "if" statements to check
the presence of elements in a list, because some of them are mutually
exclusive, so if for example there are both "3" and "no3" it should
return an error.

Thanks,
Carlo



More information about the Python-list mailing list