Reputation: 2608
I'm learning python and I stumbled upon something I don't understand.
For instance:
x = 50
while x:
print(x)
x >>= 1
Outputs:
50
25
12
6
3
1
So I infer that it divides by two and rounds to the left if it's not an integer or something similar.
But when I change it to x >>= 3 for instance the output is:
50
6
Can someone please explain what >>= does?
If so, what are useful applications of this kind of operator.
Upvotes: 1
Views: 202
Reputation: 333
It's the binary right shift operator.
For example,
if you have 0100b
, and you do: 0100b >> 2
, then as a result you will have the number 0001b
(you've shifted the one two positions to the right).
Upvotes: 4
Reputation: 1121904
>>=
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.
Upvotes: 7
Reputation: 500357
This is augmented assignment with the right shift operator.
x >>= 1
is shorthand for x = x >> 1
.
x >>= k
divides by 2**k
(i.e. 2
raised to the k
-th power).
Thus, x >>= 3
is the integer division by eight.
Upvotes: 4