Logic operators with "in" statement

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


On Mon, Nov 16, 2009 at 6:08 AM, Mr.SpOOn <mr.spoon21 at gmail.com> wrote:
> Sorry for replying to myself, but I think I understood why I was wrong.
>
> The correct statement should be something like this:
>
> In [13]: ('b3' and '5') in l or ('3' and 'b3') in l
> Out[13]: True

No, you've just run into another misunderstanding.

Given the expression `X and Y`:
If bool(X) is False, it evaluates to X.
Otherwise, it evaluates to Y.

In other words, the subexpression which ends up determining the truth
of the conjunction is what the conjunction evaluates to. `or` works
similarly.
This allows for tricky tricks like:
foo = possiblyFalse or default # use default if given value is false

Thus, due to the parentheses, your expression is equivalent to:
'5' in l or 'b3' in l
Which I trust is not what you intended.

Again, you need to write separate `in`s for each item you need to
check the membership of:
('b3' in l and '5' in l) or ('3' in l and 'b3' in l)

Cheers,
Chris
--
Python language lawyer at your service
http://blog.rebertia.com



More information about the Python-list mailing list