Search code examples
pythonoperators

What does the << / >> operator signify? (Python3)


The expression (8 >> 1) evaluates to 4. Additionally, (8 << 1) evaluates to 16. I have no idea what the double arrow operator does, does anybody know?


Solution

  • Double arrow operation is bit-shift.

    Basically, it looks at your number in binary then "shifts" your entire number to one place left, or one place right.

    For example:

    8 >> 1 ->
                 8 becomes:   00001000
    shifting 1 place right:   00000100
    which is 4.
    
    Similarly,
    8 << 1 ->
                 8 becomes:   00001000
     shifting 1 place left:   00010000
    which is 16.
    

    There are some edge cases here and there such as logical shift versus arithmetic shift.

    Usually, you can use them to do a very quick operation to multiply a number by 2 or divide them by 2, but that is language-dependent, and needs more detail to understand perfectly. In Python particularly, not so much as explained by @paxdiablo in the comments as follows:

    bit shifting left in Python is not necessarily faster than multiplication, it has optimisations to avoid expanding its arbitrary precision integers in the latter case

    More details on here: What are bitwise shift (bit-shift) operators and how do they work?