Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 666
user3201152 Avatar asked Oct 13 '22 07:10

user3201152


People also ask

What is >> and << in Python?

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.

What does mean >> in Python?

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.

What does >> mean in code?

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.

What is the difference between these two symbols and >> in Python?

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.


2 Answers

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
like image 135
yosemite_k Avatar answered Oct 19 '22 13:10

yosemite_k


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.

like image 107
James Avatar answered Oct 19 '22 13:10

James