Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The >> operator is the bitwise right shift operator. It shifts the binary representation of an integer to the right by a specified number of bit positions. Because Python integers have arbitrary precision and are conceptually represented using an infinite-width two’s complement format, the >> operator performs an arithmetic right shift, meaning it preserves the sign bit via sign extension.

Syntax

result = x >> y
  • x (Left Operand): The integer whose bits will be shifted.
  • y (Right Operand): The number of bit positions to shift x to the right. This must be a non-negative integer.

Mathematical Equivalence

The operation x >> y is strictly equivalent to the floor division of x by 2y2^y.
x >> y == x // (2 ** y)

Mechanical Behavior

1. Positive Integers

When shifting a positive integer, the rightmost y bits are discarded, and y number of 0 bits are conceptually shifted in from the left.
x = 22      # Binary: ...0001 0110
y = 2
    
result = x >> y  # Binary: ...0000 0101 (Decimal: 5)

2. Negative Integers

When shifting a negative integer, Python maintains the two’s complement sign. The rightmost y bits are discarded, and y number of 1 bits are shifted in from the left to preserve the negative value. Because the operation equates to floor division, shifting a negative number rounds towards negative infinity.
x = -22     # Binary: ...1110 1010
y = 2
    
result = x >> y  # Binary: ...1111 1010 (Decimal: -6)

# Mathematical equivalent: -22 // (2 ** 2) == -22 // 4 == -6

3. Invalid Operands

The right operand (y) must be greater than or equal to zero. Attempting to shift by a negative number results in a ValueError.
x = 10
result = x >> -1  # Raises ValueError: negative shift count
If either operand is not an integer, Python will attempt to invoke the __rshift__ (on the left operand) or __rrshift__ (on the right operand) dunder methods. If the types do not implement these methods for the given operands, Python raises a TypeError.
Master Python with Deep Grasping Methodology!Learn More