What do >> and

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

Leave a Comment