The &
is not a logical test, but an operation done with 2 integers, the result of which is another integer. To be more precise, it is a Binary bitwise Operation.
In the case, the &
makes the "and logical" bit by bit: if both bits are 1, the result is 1. If any of the bits is zero, the result is zero.
For example, you quoted 1 & 3
, that stays that way:
00000001 <-- 1 em binário
00000011 <-- 3 em binário
--------
00000001 <-- 1 & 3
That is, when both bits are 1, the resulting bit is 1, otherwise it is zero. The result is number 1.
In the case of True & False
, it is worth remembering that according to the documentation, one Boolean is a subclass of int
, and True
and False
are equal to 1 and 0 respectively.
So True & False
is the same as 1 & 0
, which, as explained above, results in zero (which in turn is equal to False
):
00000001 <-- 1 em binário
00000000 <-- 0 em binário
--------
00000000 <-- 1 & 0
And just to top it off, the >>
is a shift Operator, that moves bits to the right (has an explanation here).
Therefore the result of the expression is an integer, there is no logical test or comparison being made.
At the bottom this is a small "trick" to see if a certain bit is set. For example, for n=13 and k=2:
00001101 <-- n=13
00000011 <-- n >> k (desloca 2 posições para a direita)
00000001 <-- faz o & com 1
--------
00000001 <-- resultado é 1, indicando que o bit da posição k está setado
Now for n=9 and k=2:
00001001 <-- n=9
00000010 <-- n >> k (desloca 2 posições para a direita)
00000001 <-- faz o & com 1
--------
00000000 <-- resultado é 0, indicando que o bit da posição k não está setado
The >>
is executed first (following the order of precedence of operators), shifting the bits of n
to the right in k
positions. With that the bit of the position k
becomes the last position (considering, of course, that the last position is zero, the penultimate position is 1, etc).
Then the 1 & resultado do shift
, and the &
done with number 1 always results in 1 if the last bit is 1, and zero otherwise.
So the expression indicates if the number bit n
, of position k
, is 1 or zero (whereas the last bit is the zero position, the penultimate is the 1 position, etc).
this is wrong: "1 as True and any other number as False." - the right is that "0 is interpreted as False, and any other number as True". I’m emphasizing why this is very important and can get lost in longer responses.
– jsbueno