Sub topic 3
Python Operators and Expressions
Assume you know basic Python syntax, variables, and built-in types such as str, list, tuple, and dict. This chapter focuses on operators that test, combine, assign, and transform values.
Membership tests
in tests whether a value occurs in a container. not in reverses the result.
print(3 in [1, 2, 3])
print("py" in "python")
print("a" in {"a": 1}) # dictionary keys
print(4 not in (1, 2, 3))Membership in a string checks for a substring. Membership in a dictionary checks keys, not values.
Strings, lists, and tuples
Strings, lists, and tuples are sequences. The + operator concatenates sequences of the same type. The * operator repeats them.
print("ha" * 3)
print([1, 2] + [3, 4])
print((1, 2) + (3,))A tuple with one item needs a trailing comma: (3,).
Assignment operators
Augmented assignment updates a variable using an operator:
total = 10
total += 5
total *= 2
print(total) # 30x += y is usually similar to x = x + y. For mutable objects such as lists, it may modify the existing object instead of creating a new one.
The walrus operator
The assignment expression := assigns a value while an expression is being evaluated. Use it when avoiding repeated work improves clarity.
data = [10, 20, 30]
if (count := len(data)) > 2:
print(f"{count} items")Do not use it merely to make a short line shorter.
Bitwise operators and shifts
Bitwise operators work on the binary digits of integers.
| Operator | Meaning | Column |
|---|---|---|
| `&` | bitwise AND | |
| `\ | ` | bitwise OR |
| `^` | bitwise XOR | |
| `<<` | shift left | |
| `>>` | shift right |
flags = 0b0101
print(flags & 0b0100) # 4
print(1 << 3) # 8Precedence and associativity
Precedence determines grouping. Multiplication happens before addition, and comparisons happen before and.
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20
print(2 ** 3 ** 2) # 512Use parentheses when grouping is important or unclear.
Operator overloading
Operator overloading lets a class define what operators mean for its objects. Special methods such as __add__ implement +, while __eq__ implements ==.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
if not isinstance(other, Point):
return NotImplemented
return Point(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Point({self.x}, {self.y})"
print(Point(1, 2) + Point(3, 4))Return NotImplemented for unsupported operand types so Python can try the other operand or raise a suitable error.
Exercise
What does 2 + 3 * 4 in [14, 20] evaluate to?
Show answer
True, because multiplication happens first, making the expression 14 in [14, 20].