简体   繁体   中英

Python: What does >>= do?

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.

>>= 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.

This is augmented assignment with the right shift operator .

x >>= 1 is shorthand for x = x >> 1 .

x >>= k divides by 2**k (ie 2 raised to the k -th power).

Thus, x >>= 3 is the integer division by eight.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM