biw
biw

Reputation: 3085

What do >> and << do in python

If I do print(1 >> 2) I get 0.

If I do print(2 << 1) I get 4.

If I do print(9 << 3) I get 72

If I do print(3 >> 9) I get 0

What do >> and << do in python?

Upvotes: 1

Views: 125

Answers (2)

DickJ
DickJ

Reputation: 313

They are bitwise shift operators. For example, 2 has the binary equivalent 00000010, so 2 << 1 is 00000010 shifted left 1 time. This yields 00000100, which is 4.

1 >> 2 is 00000001 shifted right 2 times which is 00000000 (the 1 falls off the end after the first shift though, so 1>>1 is also 0), obviously that is 0.

Upvotes: 6

David Schwartz
David Schwartz

Reputation: 182761

Bitwise shift left and bitwise shift right. They're roughly equivalent to doubling (<<) or halving (>>) just like decimal shift left is roughly equivalent to multiplying by 10 and decimal shift right is roughly equivalent to dividing by 10.

Upvotes: 3

Related Questions