Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Numbers and Binary Data

Python logical and bitwise operators

Reference for Python's and, or, not and the bitwise operators &, |, ^, ~, <<, >>: short-circuit evaluation, returned values, truthiness and set operations.

Python has two families of operators that look related but behave differently. The logical operators and, or and not work on truth values and short-circuit. The bitwise operators &, |, ^, ~, << and >> work on the binary digits of integers (and on sets, for &, |, ^).

The key surprise: and and or return one of their operands, not necessarily True or False. Only not always returns a bool.

Python
0 or "default"    # "default"
5 and 7           # 7
not []            # True
6 & 3             # 2

Try it

Python and, or, not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Bitwise operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Operator Meaning
a and b If a is falsy, returns a; otherwise returns b.
a or b If a is truthy, returns a; otherwise returns b.
not a True if a is falsy, else False.
a & b Bitwise AND (set intersection)
a | b Bitwise OR (set union, dict merge)
a ^ b Bitwise XOR (symmetric difference)
~a Bitwise NOT, equal to -a - 1
a << n, a >> n Shift left or right by n bits (n must not be negative)

Raises: TypeError for unsupported operand types, such as 1.5 & 1. ValueError for a negative shift count.

Usage notes

  • Short-circuit evaluation. and stops at the first falsy operand, and or at the first truthy one. The right side may never run, which makes x and x.attr safe guards.
  • Falsy values: False, None, zero of any numeric type, and empty strings and containers. Everything else is truthy.
  • or for defaults has a catch: count = value or 10 also replaces a legitimate 0. Use value if value is not None else 10 when zero is valid.
  • and/or do not work elementwise on NumPy arrays or pandas Series. Use &, | and ~ with parentheses there.
  • Precedence. not binds tighter than and, which binds tighter than or. Bitwise operators bind tighter than comparisons, so 1 == 1 & 3 means 1 == (1 & 3); always parenthesize mixed expressions.
  • ~n is -n - 1 because Python integers behave like infinite two's-complement values. To get an unsigned width, mask the result: ~5 & 0xFF.
  • Right shift of negatives rounds toward negative infinity: -16 >> 2 is -4, and -1 >> 1 is -1.
  • & and | on bools return a bool and do not short-circuit. Use them only when you want both sides evaluated.