Assigns and returns a value in the same expression, useful inside conditionals or comprehensions.
# Without walrusdata = get_data()if data: process(data)# With walrusif (data := get_data()): process(data)# Inside a comprehension, avoids calling a function twiceresults = [y for x in values if (y := expensive(x)) > 0]
Identity vs Equality: is vs ==
a = [1, 2, 3]b = [1, 2, 3]a == b # True, same valuesa is b # False, different objects in memorya is a # True, same object
Tip
Small integers (-5 to 256) and short strings are cached by CPython, so is may accidentally return True for them. Never rely on this behavior, always use == for value comparison and is only for None/True/False/singleton checks.
Membership Operators
3 in [1, 2, 3] # True"a" in "abc" # True3 not in [1, 2, 3] # False
Bitwise Operators
5 & 3 # 1 AND5 | 3 # 7 OR5 ^ 3 # 6 XOR~5 # -6 NOT (inverts all bits)5 << 1 # 10 left shift (multiply by 2)5 >> 1 # 2 right shift (divide by 2, floor)
Operator Precedence (high to low, abbreviated)
() parentheses
** exponentiation
+x, -x, ~x unary
*, /, //, %
+, -
Comparisons, in, is
not
and
or
When in doubt, parenthesize
Relying on memorized precedence rules makes code harder to review. Adding explicit parentheses costs nothing and removes ambiguity for the next reader (often future you).