Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "and" operator on two values give the last value?

I've been tinkering a little with Python operators and came across something I'm not sure about.

If I perform a bitwise operation (&, |) on 2 integers I will get unsurprisingly their bitwise value. Meaning:

>>> a = 11
>>> b = 3
>>> a & b
3

This is because it performs bitwise AND on the binary representation of these numbers.

However, if I use the built in and operator I will get the second variable, irrespective of its type:

>>> b and a
11
>>> 'b' and 'a'
'a'

Why is it so?

like image 862
tHeReaver Avatar asked Oct 22 '25 10:10

tHeReaver


1 Answers

Logical operators operate on the truthiness of an object. Every object has truth value, unless it has a __bool__ method that is explicitly overridden to raise an error. The major difference between a and b (logical) and a & b (bitwise) is that the former apply to any objects, while the latter only apply to numeric types that support bitwise operations1.

Python's logical operators are specifically designed to return the result of the last object evaluated:

  • a and b: Returns a Falsy a, or b (if a is truthy)
  • a or b: Returns a Truthy a, or b (if a if falsy)

From the tutorial:

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

This property is used semi-idiomatically to check values before accessing them. For example, if a list must contain an element, you can do something like

if x and x[0] == value:
    # ...

This will not raise an error, because if x is Falsy (empty), the and expression will return x instead of x[0] == value.


1 Set-like objects also support & as the intersection operator. This is conceptually similar to what the bitwise operator does for integers (you can think of bits as sets), and in no way detracts from the rest of the answer.

like image 142
Mad Physicist Avatar answered Oct 24 '25 23:10

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!