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.
0 or "default" # "default" 5 and 7 # 7 not [] # True 6 & 3 # 2
Try it
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.
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.
andstops at the first falsy operand, andorat the first truthy one. The right side may never run, which makesx and x.attrsafe guards. - Falsy values:
False,None, zero of any numeric type, and empty strings and containers. Everything else is truthy. orfor defaults has a catch:count = value or 10also replaces a legitimate0. Usevalue if value is not None else 10when zero is valid.and/ordo not work elementwise on NumPy arrays or pandas Series. Use&,|and~with parentheses there.- Precedence.
notbinds tighter thanand, which binds tighter thanor. Bitwise operators bind tighter than comparisons, so1 == 1 & 3means1 == (1 & 3); always parenthesize mixed expressions. ~nis-n - 1because 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 >> 2is-4, and-1 >> 1is-1. &and|on bools return abooland do not short-circuit. Use them only when you want both sides evaluated.