-2

Can anyone explain this weird behavior?

It seems operating and between boolean lists behaves wrongly regardless of my IDE.

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
a=[True, True, False, True, False, False, False]
b=[True, False, False, True, True, True, False]
a and b
Out[4]: [True, False, False, True, True, True, False]
b and a
Out[5]: [True, True, False, True, False, False, False]
True and False
Out[6]: False
False and True
Out[7]: False
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    That's not weird behaviour, or wrong. `and` is operating on the whole list, not element-wise. Any non-empty list is [truth-y](https://docs.python.org/3/library/stdtypes.html#truth-value-testing). Did you want e.g. `[x and y for x, y in zip(a, b)]` (which would be `[True, False, False, True, False, False, False]`)? – jonrsharpe Nov 26 '19 at 23:41
  • 1
    Any nonempty list is truthy. So `and` of your two nonempty lists will just give you the second list. – khelwood Nov 26 '19 at 23:42

2 Answers2

1

and returns either the first or the second operand, based on their truth value. If the first operand is considered false, it is returned, otherwise the other operand is returned.

Lists are considered True when they are not empty. Their elements don't play a role here.

Because both lists are not empty, a and b simply returns the second list object.

If you want element-wise operation, you can do:

element-wise =  [x and y for x, y in zip(a, b)] #suggested by @johnrsharpe
Mert Köklü
  • 2,183
  • 2
  • 16
  • 20
0

Python's and will return the last of the compared items if all compared items are truthy (a and b, b and a). The statements True and False and False and True evaluate to False (your last two cases).

Zeke Marffy
  • 188
  • 3
  • 14