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.

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.
a = 12  # Binary: 1100
b = 10  # Binary: 1010

result = a & b 

# Binary evaluation:

#   1100

# & 1010

# ---

#   1000  -> Decimal: 8

print(result)  # Output: 8

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.

# Set intersection
set_x = {1, 2, 3, 4}
set_y = {3, 4, 5, 6}
set_result = set_x & set_y  # Output: {3, 4}


# Dictionary view intersection
dict_a = {'x': 1, 'y': 2}
dict_b = {'y': 99, 'z': 3}
view_result = dict_a.keys() & dict_b.keys()  # Output: {'y'}

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:
class CustomValue:
    def __init__(self, value):
        self.value = value

    def __and__(self, other):
        if isinstance(other, CustomValue):
            return CustomValue(self.value and other.value)
        return NotImplemented

    def __repr__(self):
        return f"CustomValue({self.value})"

obj1 = CustomValue(True)
obj2 = CustomValue(False)

result = obj1 & obj2
print(result)  # Output: CustomValue(False)

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:
x = 5
y = 10


# Correct logical grouping due to explicit parentheses:
result = (x > 0) & (y < 20) 


# Semantic/logical error (Valid syntax, but evaluates as `x > (0 & y) < 20`):
result = x > 0 & y < 20 
Master Python with Deep Grasping Methodology!Learn More