Logic operators with "in" statement

Xavier Ho contact at xavierho.com
Mon Nov 16 15:23:01 CET 2009

On Tue, Nov 17, 2009 at 12: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.

Hey Carlo, I think your issue here is mistaking 'in' as a statement. It's
just another logic operator, much like 'and' and 'or'... it's not a
statement in itself. At least, I don't think that's how you'd call 'in'.

You have to remember that Python's logical operators (and, or) works
slightly different than most languages. It doesn't return True or False, if
the things compared aren't boolean values. Instead, it returns the first
thing that makes the decision.

For example a statement such as

>>>'3' and '4'

returns the string literal 4.

Python's AND operator returns the first element if the first one is False;
else, it returns the second element. That's all it does.

Python's OR operator returns the first element if the first one is True;
else, it returns the second element.

Think about it. It's a little strange, but they don't return a pure Boolean

Only the empty string is considered False. Any non-empty strings have True

The proper way of using the in operator is probably such: (There may be a
better way I'm not aware of.)

>>> '3' in l and '4' in l

>>> '3' in l and 'no3' in l

AND operator has a higher precedence, so you don't need any brackets here, I
think. But anyway, you have to use it like that. So that's something you'll
have to fix first.

> 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

One idea I can think of is to have a presence count; assuming the input is
non-repeating, you increase this count by 1, starting at 0. If you get
anything above one, return this error you speak of, and that might be a good

Good luck,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091117/83bc4cef/attachment.html>

More information about the Python-list mailing list