Skip to main content
The << operator is the bitwise left shift operator in Python. It shifts the binary representation of an integer to the left by a specified number of bit positions, appending zeros to the least significant bits (the right side). Mathematically, evaluating x << y is strictly equivalent to multiplying x by 2 raised to the power of y (x×2yx \times 2^y).

Syntax

  • x (Left Operand): The base integer whose bits will be shifted.
  • y (Right Operand): The shift count. It must be a non-negative integer representing the number of positions to shift the bits.

Technical Mechanics

  1. Binary Translation: Python evaluates the binary equivalent of the base integer x.
  2. Bit Manipulation: It moves every bit y steps to the left.
  3. Zero Padding: It inserts y number of 0 bits at the rightmost end of the binary sequence.
  4. Arbitrary Precision and Limits: Unlike languages with fixed-width integers (e.g., C or Java), Python integers have arbitrary precision and do not wrap around. However, CPython enforces a maximum integer size. Shifting by an excessively large amount (e.g., 1 << 10**19) will raise an OverflowError (Python int too large to convert to C ssize_t), and shifting to a size that exceeds available system RAM will raise a MemoryError.
  5. Negative Shift Counts: Attempting to shift by a negative number (y < 0) is an illegal operation and will raise a ValueError.
  6. Operand Types: Both operands must be integers. Passing floats or strings will raise a TypeError.

Operator Precedence

The << operator has lower precedence than arithmetic operators such as addition (+) and subtraction (-), but higher precedence than bitwise AND (&), OR (|), and XOR (^). Because of this, an expression like x << y + 1 evaluates as x << (y + 1), not (x << y) + 1. Parentheses must be used to explicitly define the desired evaluation order if the shift operation should occur before arithmetic.

Execution Examples

Basic Left Shift
Visualizing the Bit Shift Using Python’s built-in bin() function demonstrates the exact bit manipulation:
Operator Precedence
Mathematical Equivalence
Error Handling for Negative Shifts
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More