Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

Operators are special symbols or keywords in Python that perform specific operations on one or more operands (variables, values, or expressions). At the interpreter level, most operators act as syntactic sugar for underlying C-level implementations or Python dunder (magic) methods (e.g., the + operator invokes the __add__ method of an object).

Arithmetic Operators

Arithmetic operators perform mathematical computations. Python supports standard arithmetic along with specialized operators for integer division, remainders, and matrix operations.
a = 10
b = 3

+a      # Unary positive (maps to __pos__)
-a      # Unary negation (maps to __neg__)
a + b   # Addition (maps to __add__)
a - b   # Subtraction (maps to __sub__)
a * b   # Multiplication (maps to __mul__)
a / b   # True Division (maps to __truediv__)
a // b  # Floor Division (maps to __floordiv__, rounds down towards negative infinity)
a % b   # Modulo (maps to __mod__, returns remainder)
a ** b  # Exponentiation (maps to __pow__)


# Matrix Multiplication (maps to __matmul__, Python 3.5+)

# Requires objects that explicitly implement the __matmul__ dunder method.
class Matrix:
    def __matmul__(self, other):
        return Matrix()

m1 = Matrix()
m2 = Matrix()
m1 @ m2 

Comparison (Relational) Operators

Comparison operators evaluate the equivalence or relative magnitude of operands. The return value is determined entirely by the underlying dunder method (e.g., __eq__, __lt__). While built-in scalar types return a boolean value (True or False), custom objects and external libraries frequently return non-boolean types (e.g., NumPy returns arrays of booleans, and SQLAlchemy returns SQL binary expression objects). Python allows chaining of comparison operators. In a chained comparison, intermediate operands are evaluated exactly once.
a = 10
b = 5
c = 15

a == b     # Equal to (maps to __eq__)
a != b     # Not equal to (maps to __ne__)
a > b      # Greater than (maps to __gt__)
a < b      # Less than (maps to __lt__)
a >= b     # Greater than or equal to (maps to __ge__)
a <= b     # Less than or equal to (maps to __le__)


# Chained comparison
a < b <= c # Evaluates 'b' exactly once. 
           # Semantically similar to 'a < b and b <= c', but avoids double evaluation of 'b' 
           # which is critical if 'b' is a function call with side effects.

Logical Operators

Logical operators perform boolean logic. The and and or operators utilize short-circuit evaluation, meaning the interpreter stops evaluating the expression as soon as the outcome is determined. These two operators return the actual operand value that resolved the expression, not necessarily a strict boolean. Conversely, the not operator is a unary operator that evaluates the truthiness of its operand and always returns a strict boolean.
a = True
b = False

a and b # Logical AND: Returns 'a' if 'a' is falsy; otherwise returns 'b'
a or b  # Logical OR: Returns 'a' if 'a' is truthy; otherwise returns 'b'
not a   # Logical NOT: Returns True if 'a' is falsy, False if 'a' is truthy

Bitwise Operators

Bitwise operators treat operands as sequences of binary digits and operate on them bit-by-bit when applied to integers. These operators are also frequently overloaded by other data types, such as built-in set objects (where &, |, and ^ perform intersection, union, and symmetric difference) and external libraries like NumPy.
a = 10  # Binary: 1010
b = 4   # Binary: 0100

a & b   # Bitwise AND (maps to __and__)
a | b   # Bitwise OR (maps to __or__)
a ^ b   # Bitwise XOR (maps to __xor__)
~a      # Bitwise NOT (maps to __invert__, equivalent to -(a + 1) for integers)
a << 1  # Bitwise Left Shift (maps to __lshift__)
a >> 1  # Bitwise Right Shift (maps to __rshift__)

Assignment Operators

Assignment operators bind values to variable names (references). Python supports augmented assignment operators, which combine an arithmetic or bitwise operation with assignment. Augmented assignment always rebinds the variable name to the result of the operation. For mutable objects implementing the corresponding in-place dunder method (e.g., __iadd__), the method modifies the object in place and returns self, meaning the variable is rebound to the exact same object reference. For immutable objects (or objects lacking the in-place method), the operation evaluates to a newly created object, and the variable name is rebound to that new object.
a = 10
b = 5

a = b     # Standard assignment
a += b    # Addition assignment (maps to __iadd__ or __add__)
a -= b    # Subtraction assignment (maps to __isub__ or __sub__)
a *= b    # Multiplication assignment (maps to __imul__ or __mul__)
a /= b    # Division assignment (maps to __itruediv__ or __truediv__)


# Assignment Expression (Walrus Operator) - Python 3.8+

# Assigns a value to a variable and returns that value simultaneously.
(c := b)  

Identity Operators

Identity operators evaluate object identity, not object equality. They check whether two operands point to the exact same memory address (i.e., the same underlying object).
a = [1, 2]
b = a
c = [1, 2]

a is b      # Returns True (id(a) == id(b))
a is not c  # Returns True (id(a) != id(c), even though a == c is True)

Membership Operators

Membership operators test for the presence of a value within a sequence or collection (such as strings, lists, tuples, sets, or dictionaries).
a = 1
b = [1, 2, 3]

a in b      # Returns True if 'a' is an element of 'b' (maps to __contains__)
4 not in b  # Returns True if 4 is not an element of 'b'

The operator Module

Python provides the operator standard library module, which exports all built-in syntax operators as callable C-optimized functions. This is utilized when a function reference is required for higher-order functions (like map(), filter(), or functools.reduce()) instead of a syntax symbol.
import operator

a = 10
b = 5
c = complex(1, 2)
seq = [10, 20, 30]

operator.add(a, b)               # Equivalent to a + b
operator.eq(a, b)                # Equivalent to a == b
operator.contains(seq, a)        # Equivalent to a in seq
operator.itemgetter(1)(seq)      # Equivalent to seq[1]
operator.attrgetter('real')(c)   # Equivalent to c.real
Master Python with Deep Grasping Methodology!Learn More