Python Operators
Operators & Expressions
Python Operators
Operators are the glue between values and expressions. Get fluent in the categories, precedence rules, and edge cases that power control flow and data processing.
Operator categories
| Category | Examples | Notes |
|---|---|---|
| Arithmetic | +, -, *, /, //, %, ** | Numeric math; // is floor division |
| Comparison | ==, !=, <, >, <=, >= | Return booleans |
| Logical | and, or, not | Short-circuit evaluation |
| Assignment | =, +=, -=, *=, /= | Combine operation + assignment |
| Bitwise | &, ` | , ^, ~, <<, >>` |
| Identity | is, is not | Compare object identity |
| Membership | in, not in | Check containment (strings, lists, sets, dicts) |
Precedence
| Level | Operators |
|---|---|
| 1 | Parentheses `( )` |
| 2 | Exponentiation `**` |
| 3 | Unary `+x`, `-x`, `~x` |
| 4 | Multiplication, division, floor division, modulus |
| 5 | Addition, subtraction |
| 6 | Bitwise shifts |
| 7 | Bitwise AND, XOR, OR |
| 8 | Comparisons, `in`, `is` |
| 9 | Logical `not`, `and`, `or` |
| 10 | Assignment operators |
When in doubt, add parentheses to make intent explicit.
Short-circuit logic
user = session_user or fetch_user()
orreturns the first truthy operand.andreturns the first falsy operand (or the last operand if all truthy).
Use this for lazy evaluation but avoid chaining complex expressions that sacrifice readability.
Identity vs equality
a = [1, 2]
b = [1, 2]
print(a == b) # True (values equal)
print(a is b) # False (different objects)
Use is only for singleton checks (e.g., is None). Use == for value comparison.
Assignment expressions (walrus operator)
Available since Python 3.8:
if (line := file.readline()):
process(line)
Use sparingly to avoid confusing readers. Great for loops that read from generators or expensive functions.
Next up in your learning path
Frequently Asked Questions
Why does `True == 1` evaluate to True?
Booleans are subclasses of integers (`True` equals `1`, `False` equals `0`). For strict comparisons, ensure you compare to `True`/`False` explicitly or use `isinstance` checks.
What's the difference between `/` and `//`?
`/` performs floating-point division and always returns `float`. `//` performs floor division, returning the integer quotient (floored) for numeric types.
Should I use bitwise operators in everyday code?
Only when working with low-level data (flags, binary protocols) or performance-sensitive tasks. For most Python applications, higher-level abstractions are clearer.