Skip to main content

Python, Explained — Variables That Aren’t What They Seem

·367 words·2 mins
Rich
Author
Rich

When I first started learning Python, I thought variables behaved the same way they did in other languages I’d played with.
Assign a value, copy a value, change one, and the other should stay the same… right?

Well, not quite.

Consider this tiny snippet that really confused me in the beginning:

VariableA = 1
VariableB = VariableA
VariableA =+ 1
print(VariableB)

At first glance, I expected:

1

But Python printed:

2

What?!


The Confusion
#

I assumed that VariableB held its own copy of the value 1 at the moment it was assigned.
So when VariableA changed later, surely VariableB should remain untouched.

What I didn’t realise was:

  1. Variables in Python don’t store data—they store references to objects
    VariableA doesn’t “contain” 1. It points to the integer object 1.

  2. When you do:

    VariableB = VariableA

    you’re not copying the value — you’re copying the reference.

  3. And then… the biggest “aha” moment:

    VariableA =+ 1

    is not the same as:

    VariableA += 1

    The version with =+ simply assigns positive 1 to the variable.

    So this line:

    VariableA =+ 1

    means:

    VariableA = +1

    You are reassigning VariableA to the integer 1 again — not incrementing it.

    Which means the code is actually doing this under the hood:

    VariableA = 1
    VariableB = 1
    VariableA = 1  # again
    print(1)

So why did your version print 2?
Because in your real test, you probably used +=, not =+.

And that difference is where Python once confused a lot of us.


The Real Behaviour (with +=)
#

If you intended to increment VariableA, the correct operator is:

VariableA += 1

Now we get:

VariableA = 1
VariableB = VariableA  # both reference '1'
VariableA += 1         # VariableA now references a NEW '2' object
print(VariableB)       # still '1'

And the output becomes:

1

Because integers are immutable in Python — modifying them actually creates a new object.


Why This Mattered to Me
#

This tiny detail: =+ vs +=, “references vs values” or “immutability vs mutability”. The first time I realised Python had its own internal logic that didn’t always match what I assumed. You know what they say about assumption - it makes a fool of us both!

Related