How to interpret boolean operation on integers?

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?

1 answer

  • answered 2020-11-25 06:43 gilch

    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.