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?
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.
In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand. Leading bits as towards left as a result of shifting are set to 0.
The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.
In Python and many other programming languages, a single equal mark is used to assign a value to a variable, whereas two consecutive equal marks is used to check whether 2 expressions give the same value . (x==y) is False because we assigned different values to x and y.
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 a bitwise operator (right shift),
2 << 5 # shift left by 5 bits
# 0b10 -> 0b1000000
1000 >> 2 # shift right by 2 bits
# 0b1111101000 -> 0b11111010
While in the second scenario it is used for output redirection. You use it with file objects, like this example:
with open('foo.txt', 'w') as f:
print >>f, 'Hello world' # "Hello world" now saved in foo.txt
This second use of >> only worked on Python 2. On Python 3 it is possible to redirect the output of print() using the file= argument:
with open('foo.txt', 'w') as f:
print('Hello world', file=f) # "Hello world" now saved in foo.txt
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With