[python] What do >> and << mean in Python?

I notice that I can do things like 2 << 5 to get 64 and 1000 >> 2 to get 250.

Also I can use >> in print:

print >>obj, "Hello world"

What is happening here?

This question is related to python syntax operator-keyword

The answer is


<< Mean any given number will be multiply by 2the power
for exp:- 2<<2=2*2'1=4
          6<<2'4=6*2*2*2*2*2=64

12 << 2

48

Actual binary value of 12 is "00 1100" when we execute the above statement Left shift ( 2 places shifted left) returns the value 48 its binary value is "11 0000".

48 >> 2

12

The binary value of 48 is "11 0000", after executing above statement Right shift ( 2 places shifted right) returns the value 12 its binary value is "00 1100".


These are the shift operators

x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.


They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.

| operate | bit value | octal value |                       description                        |
| ------- | --------- | ----------- | -------------------------------------------------------- |
|         | 00000100  |           4 |                                                          |
| 4 << 2  | 00010000  |          16 | move all bits to left 2 bits, filled with 0 at the right |
| 16 >> 2 | 00000100  |           4 | move all bits to right 2 bits, filled with 0 at the left |

These are bitwise shift operators.

Quoting from the docs:

x << y

Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y

Returns x with the bits shifted to the right by y places. This is the same as dividing x by 2**y.


I think it is important question and it is not answered yet (the OP seems to already know about shift operators). Let me try to answer, the >> operator in your example is used for two different purposes. In c++ terms this operator is overloaded. In the first example it is used as bitwise operator (left shift), while in the second scenario it is merely used as output redirection. i.e.

2 << 5 # shift to left by 5 bits
2 >> 5 # shift to right by 5 bits
print >> obj, "Hello world" # redirect the output to obj, 

example

with open('foo.txt', 'w') as obj:
    print >> obj, "Hello world" # hello world now saved in foo.txt

update:

In python 3 it is possible to give the file argument directly as follows:

print("Hello world", file=open("foo.txt", "a")) # hello world now saved in foo.txt

I verified the following on both Python 2.7 and Python 3.8

I did print(100<<3) Converting 100 to Binary gives 1100100. What I did is I droped the first 3 bits and added 3 bits with the value '0' at the end. So it should result as 0100000, and I converted this to Decimal and the answer was 32.

For my suprise when I executed print(100<<3) the answer was 800. I was puzzled. I converted 800 to Binary to check whats going on. And this is what I got 1100100000.

If you see how 800 was Python answer, they did not shift or drop the first 3 bits but they added value '0' to last 3 bits.

Where as print(100>>3) , worked perfect. I did manual calculation and cheked the print result from python. It worked correctly. Dropped last 3 bits and added value '0' to first 3 bits.

Looks like (100<<3) , left shift operator has a bug on Python.


The other case involving print >>obj, "Hello World" is the "print chevron" syntax for the print statement in Python 2 (removed in Python 3, replaced by the file argument of the print() function). Instead of writing to standard output, the output is passed to the obj.write() method. A typical example would be file objects having a write() method. See the answer to a more recent question: Double greater-than sign in Python.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to operator-keyword

What does double question mark (??) operator mean in PHP How to use comparison operators like >, =, < on BigDecimal What do >> and << mean in Python? How do operator.itemgetter() and sort() work? ' << ' operator in verilog Overloading operators in typedef structs (c++) C++ Double Address Operator? (&&) Concatenating strings doesn't work as expected