Skip to main content
The & operator in Python is a binary operator that performs a bitwise AND operation on integer operands, or a set intersection operation on set, frozenset, and dictionary view objects (dict_keys and dict_items). Its behavior is strictly determined by the data types of the objects it evaluates and can be overridden in custom classes using Python’s data model.

Distinction from Logical and

A critical distinction in Python is the difference between the & operator and the and keyword. The & operator always evaluates both the left and right operands and invokes the underlying __and__ method of the objects. It does not short-circuit. Conversely, the and keyword is a boolean logical operator that performs short-circuit evaluation; it evaluates the right operand if and only if the left operand is truthy, and it never invokes the __and__ method.

Integer Operands: Bitwise AND

When applied to integers, the & operator evaluates the binary representations of both operands. It compares each bit of the first operand to the corresponding bit of the second operand. The resulting bit is set to 1 if and only if both corresponding bits are 1; otherwise, the resulting bit is 0.

Collection Operands: Set Intersection

When applied to set, frozenset, or Python 3 dictionary views (dict_keys and dict_items), the & operator acts as the intersection operator. It evaluates both collections and returns a new collection containing only the unique elements that exist in both the left and right operands.

Object-Level Implementation (Dunder Methods)

At the interpreter level, the & operator is syntactic sugar for the __and__ magic method. When x & y is executed, Python attempts to call x.__and__(y). If the left operand does not support the operation with the right operand (returning NotImplemented), Python falls back to the right operand’s reverse AND method, y.__rand__(x). You can define the & operator’s behavior for custom objects by implementing these methods:

Operator Precedence

The & operator has a specific position in Python’s operator precedence hierarchy. It evaluates:
  • Lower than arithmetic operators (+, -, *, /, **) and bitwise shifts (<<, >>).
  • Higher than bitwise XOR (^), bitwise OR (|), and all comparison operators (==, >, <, etc.).
Because it binds more tightly than comparison operators, parentheses are strictly required when combining & with comparisons in a single expression to achieve the intended evaluation order:
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More