Logic operators with "in" statement

Chris Rebert clp2 at rebertia.com
Mon Nov 16 09:21:10 EST 2009


On Mon, Nov 16, 2009 at 6:02 AM, Mr.SpOOn <mr.spoon21 at gmail.com> wrote:
> 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.

No, it doesn't. You are misinterpreting. Membership tests via `in` do
NOT distribute over `and` and `or`.

'3' and '4' in l
is equivalent to:
('3') and ('4' in l)

Recall that non-empty sequences and containers are conventionally True
in Python, so your expression is logically equivalent to:
'4' in l
With '3' not being checked for membership at all.

To check multiple items for membership in a contains, you must write
each `in` test separately and then conjoin then by the appropriate
boolean operator:

'3' in l and '4' in l

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list