0

I have been playing with Python for a while. I recently discovered that when you use the built-in functions or and and on lists, you get a strange result.

What I know

According with the official documentation, the functions should work as their logical pairs do

Boolean Operations — and, or, not from (Official Documentation)

and these operators are, by default, configured for work with list.

The issue (doubt)

The strange thing came when I tried to use these functions with list. It happens that the functions seem to be interchanged.

How to reproduce it

Separately the functions seem to work fine

>>> True and True
True
>>> True and False
False
>>> False and False
False
>>> 
>>> True or True
True
>>> False or True
True
>>> False or False
False

We define the lists a,b as

>>> a = [ True, False, False]
>>> b = [ True, False,  True]
>>> 
>>> a and b
[True, False, True]
>>> a or b
[True, False, False]

Practical

I encountered this problem when trying to create a logical interface for a class utility. At the end, for some situations, I decided to create a class Proposition and overload its operators to receive the expected. But I am left wondering about this behavior.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
bench
  • 136
  • 8
  • 2
    Where did you get the idea that the operators would automatically work elementwise over lists? The documentation you linked doesn't say that. – user2357112 Aug 28 '20 at 19:26
  • The link clearly explains what's going on in these examples, once you realise that non-empty lists are considered "true" in Python (and empty ones "false). – Robin Zigmond Aug 28 '20 at 19:28
  • 1
    (which is explained in the section above, if you scroll up a bit in the docs) – user2357112 Aug 28 '20 at 19:29

0 Answers0