13 Python Quirks That Will Surprise You

The Hidden Mechanics of Python Objects

Python often feels like magic until it doesn't. You write code that seems perfectly logical, only to have the interpreter throw a curveball that leaves you questioning your sanity. These aren't just bugs; they are the result of deep-seated design decisions in

that prioritize performance or historical consistency over immediate intuition. Understanding these quirks is the difference between a developer who merely writes code and one who truly understands the
Python
runtime. Let's peel back the curtain on some of the most surprising behaviors you'll encounter.

13 Python Quirks That Will Surprise You
13 Python Quirks That Will Surprise You

Memory Optimization and the Integer Cache

One of the most jarring realizations for new developers is that the identity operator (is) doesn't always behave like the equality operator (==). This stems from a performance optimization known as integer caching. To save memory,

pre-allocates small integers—typically between -5 and 256. When you create a variable with the value 10,
Python
simply points that variable to the pre-existing object in memory.

However, move outside this range, and the behavior changes. If you define two variables as 257,

creates two distinct objects. An identity check will return False. This gets even more complex because the
CPython
interpreter might optimize literals in the same code block, caching even larger numbers. Relying on is for value comparison is a dangerous game; always stick to == unless you are specifically checking if two variables point to the exact same memory address.

The Trap of Default Mutable Arguments

We have all done it: defined a function with a default argument like def add_item(item, items=[]). It looks clean, but it hides a massive pitfall. In

, default arguments are evaluated only once at the time of function definition, not every time the function is called.

This means that the empty list [] is created once and persists across every single call to that function. If you append an item to it, that item stays there for the next caller. This shared state can lead to

13 Python Quirks That Will Surprise You

Fancy watching it?

Watch the full video and context

2 min read