Fundamentals 16 min read

WTF Python: Unexpected Behaviors and Intriguing Edge‑Case Examples

This article presents a curated collection of surprising Python examples that reveal counter‑intuitive behaviors such as string interning, dictionary key collisions, loop variable scope, generator evaluation timing, the difference between 'is' and '==', and closure capture, providing detailed explanations and code demonstrations for each case.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
WTF Python: Unexpected Behaviors and Intriguing Edge‑Case Examples

Python is a high‑level language with many conveniences, but some of its output and behavior can be puzzling for newcomers. This guide gathers a series of unintuitive examples—often called “WTF Python”—and explains the underlying mechanisms that make them work.

Structure of each example

Every entry follows the same pattern: a short title, optional notes, the code snippet, the actual output, and a concise explanation of why the result occurs.

String interning

Python reuses immutable objects in certain cases. For example, two identical short strings share the same id :

<code>a = "some_string"
id(a)
id("some" + "_" + "string")  # same id as a</code>

Only strings of length 0 or 1 are always interned; longer strings are interned when they consist solely of letters, digits, or underscores.

Dictionary key handling

Dictionary look‑ups compare both hash values and equality. Different objects with the same hash (e.g., 5 and 5.0 ) are treated as the same key:

<code>some_dict = {}
some_dict[5.5] = "Ruby"
some_dict[5.0] = "JavaScript"
some_dict[5]   = "Python"
# 5 and 5.0 resolve to the same entry, overwriting the previous value</code>

Loop variable scope

Assigning to the loop variable inside the body does not affect the iterator. The next iteration still supplies the next value from the iterator:

<code>for i in range(4):
    print(i)
    i = 10  # does not change the loop progression</code>

Generator evaluation timing

In a generator expression, the in clause is evaluated when the generator is created, while the if clause is evaluated during iteration. Changing the iterable after creation can therefore affect the result:

<code>array = [1, 8, 15]
g = (x for x in array if array.count(x) > 0)
array = [2, 8, 22]
list(g)  # yields [8] only</code>

Identity vs. equality

The is operator checks object identity, while == checks value equality. Small integers (e.g., 256 ) are pre‑allocated and therefore share identity, but larger integers (e.g., 257 ) are created anew unless assigned on the same line:

<code>a = 256; b = 256
a is b          # True
c = 257; d = 257
c is d          # False
c, d = 257, 257
c is d          # True</code>

Return in try…finally

A return in the try block is overridden by a later return in the finally block, because the finally clause always executes last:

<code>def some_func():
    try:
        return "from_try"
    finally:
        return "from_finally"
# some_func() returns "from_finally"</code>

Closure capture

Functions defined inside a loop capture the loop variable itself, not its value at definition time. All generated functions therefore return the final loop value unless the variable is passed as a default argument:

<code>funcs = []
for x in range(7):
    def some_func(x=x):
        return x
    funcs.append(some_func)
[func() for func in funcs]  # yields [0, 1, 2, 3, 4, 5, 6]</code>

Other quirks

Mutable default arguments can lead to unexpected shared state.

Using list multiplication for a 2‑D board creates rows that reference the same list, causing updates to affect all rows.

Operator precedence with is not differs from is (not …) and must be written carefully.

Overall, the collection demonstrates how Python’s implementation details—such as object interning, peephole optimizations, and closure semantics—can produce results that feel “WTF” at first glance, but become clear once the underlying principles are understood.

pythonProgrammingTutorialexamplesLanguageEdge CasesInterning
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.