>>=
is the augmented assignment statement for the >>
right-shift operator. For immutable types such as int
it is exactly the same thing as:
x = x >> 1
right-shifting the bits in x
one step to the right.
You can see what it does if you print the binary representation of x
first:
>>> x = 50
>>> format(x, '08b')
'00110010'
>>> x >>= 1
>>> format(x, '08b')
'00011001'
>>> x = 50
>>> x >>= 3
>>> format(x, '08b')
'00000110'
>>> x
6
Each shift to the right is equivalent to a floor division by 2; 3 shifts thus is as if x
was divided by 2 to the power 3, then floored to an integer.
The complementary operator is the left-shift <<
operator, multiplying the left-hand integer by 2; it is a binary power-of-two operator:
>>> x = 6
>>> format(x, '08b')
'00000110'
>>> x <<= 3
>>> x
48
>>> format(x, '08b')
'00110000'
Augmented assignment operators can differ in behaviour when applied to mutable types such as a list object, where the operation can take place in-place. For example, listobj += [1, 2, 3]
will alter listobj
itself, not create a new list object, as if listobj.extend([1, 2, 3])
was called.