-2

Let's say we want to perform a "bitwise and" operation on two integers, say, 5 and 7. It makes sense that the result should be 5 because a union of 111 and 101 should return 101 and this is of course what I get in Python:

5 & 7

Out: 5

I though that boolean and should not apply to non-boolean values, but to my surprise:

5 and 7
Out: 7

1.5 and 1.7
Out: 1.7

[1,2,3] and [4,5]
Out: [4, 5]

Now I'm confused. This works for some reason, but what does it mean? How are these values produced?

NotAName
  • 3,821
  • 2
  • 29
  • 44
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). Stack Overflow is not intended to replace existing tutorials and documentation. – Prune Nov 25 '20 at 06:46

1 Answers1

0

Python's and returns its left operand if it evaluates false, its right operand otherwise.

Python's or returns its left operand if it evaluates true, its right operand otherwise.

Note that with boolean operands, this produces the proper truth table. They're also guaranteed to not evaluate the right operand at all when they pick the left one.

Objects in Python are true unless it's a "zero", including collections of zero length.

gilch
  • 10,813
  • 1
  • 23
  • 28