# Assignment vs Copy in Python — The Bug That Looks Innocent

Many production bugs don’t come from complex algorithms. They come from misunderstanding how variables work. Python’s behavior around assignment is simple — but not intuitive.

Variables in Python are not containers of data. They are bindings to objects.

Until you internalize that distinction, mutability will continue to surprise you — especially in larger systems where shared state becomes difficult to reason about.

* * *

## The Innocent Code

```plaintext
a = [1, 2, 3]
b = a
b.append(4)

print(a)
```

Output:

```plaintext
[1, 2, 3, 4]
```

Why did `a` change when we modified `b`?

Because `b = a` does not create a new list.

It creates a new reference pointing to the same list object in memory.

* * *

## Assignment Is Not Copying

In Python:

*   Assignment binds a name to an object.
    
*   It does not duplicate the object.
    

You can prove it:

```plaintext
a = [1, 2, 3]
b = a

print(id(a))
print(id(b))
```

Output:

```plaintext
138158444153280
138158444153280
```

Same memory address → same object.

Both variables point to the same list.

* * *

## When Mutation Propagates

```plaintext
a = [10, 20]
b = a

b.append(30)

print(a)  # [10, 20, 30]
```

You modified the object. Both references see the change.

This is called **shared mutability**.

* * *

## When It Does NOT Propagate

```plaintext
a = [10, 20]
b = a.copy()

b.append(30)

print(a)  # [10, 20]
```

Now `b` refers to a different object.

* * *

## Why This Matters in Real Systems

Imagine this in a backend API:

*   You receive request data.
    
*   You assign it to another variable.
    
*   You modify it before saving.
    
*   Downstream logic reads mutated state.
    

Suddenly your middleware behaves unpredictably.

These are the hardest bugs to trace.

* * *

## The Mental Model

Think of variables as labels.

Multiple labels can stick to the same box.

Assignment creates another label.

Copy creates another box.

That difference is everything.

* * *

## Key Takeaways

*   **Assignment (**`=`**) is a label**, not a copy.
    
*   **Mutation is contagious**; if two variables share an object, they share its changes.
    
*   **When in doubt,** use `deepcopy()` when working with nested mutable structures — but understand the cost
