> ## 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.

# Python Bitwise AND

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`.

```python theme={"dark"}
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.

```python theme={"dark"}

# 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:

```python theme={"dark"}
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:

```python theme={"dark"}
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 
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
