Skip to main content

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​

CategoryExamplesNotes
Arithmetic+, -, *, /, //, %, **Numeric math; // is floor division
Comparison==, !=, <, >, <=, >=Return booleans
Logicaland, or, notShort-circuit evaluation
Assignment=, +=, -=, *=, /=Combine operation + assignment
Bitwise&, |, ^, ~, <<, >>Operate on integer bits
Identityis, is notCompare object identity
Membershipin, not inCheck containment (strings, lists, sets, dicts)

Precedence​

Precedence from highest to lowest
LevelOperators
1Parentheses `( )`
2Exponentiation `**`
3Unary `+x`, `-x`, `~x`
4Multiplication, division, floor division, modulus
5Addition, subtraction
6Bitwise shifts
7Bitwise AND, XOR, OR
8Comparisons, `in`, `is`
9Logical `not`
10Logical `and`
11Logical `or`
12Assignment operators

When in doubt, add parentheses to make intent explicit.

Short-circuit logic​

user = session_user or fetch_user()
  • or returns the first truthy operand.
  • and returns 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.