Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

>> operator in Python

What does the >> operator do? For example, what does the following operation 10 >> 1 = 5 do?

like image 422
AlexBrand Avatar asked Aug 05 '10 04:08

AlexBrand


3 Answers

It's the right bit shift operator, 'moves' all bits once to the right.

10 in binary is

1010

shifted to the right it turns to

0101

which is 5

like image 198
Eton B. Avatar answered Oct 14 '22 00:10

Eton B.


>> and << are the Right-Shift and Left-Shift bit-operators, i.e., they alter the binary representation of the number (it can be used on other data structures as well, but Python doesn't implement that). They are defined for a class by __rshift__(self, shift) and __lshift__(self, shift).

Example:

>>> bin(10) # 10 in binary
1010
>>> 10 >> 1 # Shifting all the bits to the right and discarding the rightmost one
5 
>>> bin(_) # 5 in binary - you can see the transformation clearly now
0101 

>>> 10 >> 2 # Shifting all the bits right by two and discarding the two-rightmost ones
2
>>> bin(_)
0010

Shortcut: Just to perform an integer division (i.e., discard the remainder, in Python you'd implement it as //) on a number by 2 raised to the number of bits you were shifting.

>>> def rshift(no, shift = 1):
...     return no // 2**shift
...     # This func will now be equivalent to >> operator.
...
like image 29
Yatharth Agarwal Avatar answered Oct 14 '22 00:10

Yatharth Agarwal


You can actually overloads right-shift operation(>>) yourself.

>>> class wierd(str): 
... def __rshift__(self,other): 
... print self, 'followed by', other 
... 
>>> foo = wierd('foo') 
>>> bar = wierd('bar') 
>>> foo>>bar 
foo followed by bar 

Reference: http://www.gossamer-threads.com/lists/python/python/122384

like image 29
Alan Dong Avatar answered Oct 14 '22 01:10

Alan Dong