Operators
Operators are the symbols that combine or compare values: +, -, *, /, ==, is, and, and the rest. Each one is a method call on the operands' types, which is why + concatenates strings and adds numbers.
Detailed Explanation
An operator looks like punctuation and behaves like a function. a + b is a.__add__(b) if that method exists and does not return NotImplemented. Otherwise Python tries b.__radd__(a). If both decline, you get TypeError. That protocol is how a class can support + without changing the language, and how 3 + Decimal("0.1") still works: int does not know Decimal, so Decimal.__radd__ takes over.
Arithmetic operators do not all share one numeric type. +, -, and * on two ints stay in int. / always produces a float, even for 10 / 2. Integer division is //, and remainder is %. divmod(a, b) returns both. Negative numbers follow the sign of the divisor for %, so -7 % 3 is 2, not -1. That surprises people coming from C.
Comparison operators are ==, !=, <, <=, >, >=. They return booleans unless a type overrides them to return something else, as NumPy arrays do. Chaining is a real language feature: 0 <= x < 10 means 0 <= x and x < 10, and x is evaluated once. It is not (0 <= x) < 10, which would compare a boolean to 10.
Identity and membership are separate. is asks whether two names point at the same object. in asks whether a value is present, and it is container.__contains__(item) or a fallback scan. not in and is not are their own operators, not compositions you should split across lines.
Boolean operators and, or, and not short-circuit. Bitwise operators &, |, ^, ~, <<, and >> do not short-circuit and work on integers bit by bit. Mixing them up is a bug: if flag & mask: is a bit test, if flag and mask: is a truthiness test of both values.
Assignment is not an expression. a = 1 does not produce a value you can nest. The exception is the walrus operator :=, which assigns and yields the value. Augmented assignment (+=, *=) tries an in-place method (__iadd__) first and falls back to a = a + b. For lists += mutates; for tuples it reallocates.
Operator precedence is the usual arithmetic order, with ** binding tightest among the arithmetic operators and or binding loosest among the boolean ones. When a line is hard to read, use parentheses. Precedence tables are not a readability strategy.
Code Examples
# `/` is true division. `//` is floor division.
print(10 / 2) # 5.0 <- float, even though it divides evenly
print(10 // 3) # 3
print(-7 % 3) # 2 <- sign follows the divisor
# Comparison chaining evaluates the middle name once.
x = 4
print(0 <= x < 10) # True
print(1 < 2 < 1) # False, because 2 < 1 is False# `is` is identity. `==` is value. `in` is membership.
session = {"user": "ada"}
alias = session
copy = {"user": "ada"}
print(session is alias) # True, same object
print(session == copy) # True, same keys and values
print(session is copy) # False
print("user" in session) # True, key membership for dicts# Augmented assignment on a list mutates; on a tuple it rebuilds.
cart = ["sku-1"]
other = cart
cart += ["sku-2"] # list.__iadd__, same object
print(other) # ['sku-1', 'sku-2']
pair = (1, 2)
pair += (3,) # new tuple, rebinds the name
print(pair) # (1, 2, 3)Common Gotchas
`is` is not equality
`256 is 256` can be true because of interning, then fail for `257` in the REPL. Compare values with `==`. Use `is` for `None`, `True`, `False`, and sentinels.
`+=` on a list is not `=` of a concatenation
`cart += extra` changes every alias of `cart`. `cart = cart + extra` builds a new list and leaves aliases pointing at the old one.
Bitwise `and` is `&`, boolean `and` is `and`
`if status & 0x04` tests a bit. `if status and 0x04` is true whenever `status` is non-zero.
`/` never returns an `int`
`10 / 2` is `5.0`. If you need an integer, use `//` or `divmod`.