Fundamentals 11 min read

Why Python Behaves Unexpectedly: 10 Surprising Code Quirks Explained

This article explores ten puzzling Python behaviors—from implicit dictionary key conversion and generator timing quirks to list‑iteration deletions, else clause nuances, the difference between is and ==, loop variable leakage, + versus +=, try‑finally returns, mutable True/False assignments, and subtle for‑loop mechanics—providing clear explanations and code examples for each.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Why Python Behaves Unexpectedly: 10 Surprising Code Quirks Explained

1. Implicit Conversion of Dictionary Keys

some_dict = {}
some_dict[5.5] = "Ruby"
some_dict[5.0] = "JavaScript"
some_dict[5] = "Python"

Output:

>> some_dict
{5.0: "Python", 5.5: "Ruby"}
>>> some_dict[5.5]
"Ruby"
>>> some_dict[5.0]
"Python"
>>> some_dict[5]
"Python"

Reason: Python compares dictionary keys by their hash values; since hash(5) == hash(5.0) is True, the integer key is implicitly converted to the float key.

2. Generator Execution‑Time Difference

array = [1, 8, 15]
g = (x for x in array if array.count(x) > 0)
array = [2, 8, 22]

Output:

>> print(list(g))
[8]

Reason: In a generator expression, the in part is evaluated when the generator is defined, while the if part is evaluated at iteration time, so the reassigned array affects the result.

3. Deleting Items While Iterating a List

list_1 = [1, 2, 3, 4]
list_2 = [1, 2, 3, 4]
list_3 = [1, 2, 3, 4]
list_4 = [1, 2, 3, 4]
for idx, item in enumerate(list_1):
    del item
for idx, item in enumerate(list_2):
    list_2.remove(item)
for idx, item in enumerate(list_3[:]):
    list_3.remove(item)
for idx, item in enumerate(list_4):
    list_4.pop(idx)

Output:

>> list_1
[1, 2, 3, 4]
>>> list_2
[2, 4]
>>> list_3
[]
>>> list_4
[2, 4]

Reason: Only the slice copy ( list_3[:]) is safe. del item removes the loop variable, not the list element. Removing items from the original list while iterating leads to skipped elements because the index shifts.

4. Different Handling of else

def does_exists_num(l, to_find):
    for num in l:
        if num == to_find:
            print("Exists!")
            break
    else:
        print("Does not exist")

Output:

>> some_list = [1, 2, 3, 4, 5]
>>> does_exists_num(some_list, 4)
Exists!
>>> does_exists_num(some_list, -1)
Does not exist

For try/else:

try:
    pass
except:
    print("Exception occurred!!!")
else:
    print("Try block executed successfully...")

Output:

Try block executed successfully...

Reason: The else after a for runs only if the loop completes without break. The else after try runs when no exception is raised.

5. The is Operator

a = 256
b = 256
print(a is b)   # True

a = 257
b = 257
print(a is b)   # False

Reason: is checks object identity, while == checks value equality. Small integers (‑5 to 256) are cached and thus share the same object; larger integers are distinct objects.

6. Loop Variable Leakage

# Segment 1
for x in range(7):
    if x == 6:
        print(x, ': for x inside loop')
print(x, ': x in global')
>> 6 : for x inside loop
6 : x in global
# Segment 2 (x pre‑initialized)
x = -1
for x in range(7):
    if x == 6:
        print(x, ': for x inside loop')
print(x, ': x in global')
>> 6 : for x inside loop6 : x in global
# Segment 3 (list comprehension)
x = 1
print([x for x in range(5)])
print(x, ': x in global')

Python 2.x output:

[0, 1, 2, 3, 4](4, ': x in global')

Python 3.x output:

[0, 1, 2, 3, 4]1 : x in global

Reason: In Python 2, list comprehensions leak the loop variable into the surrounding scope; Python 3 isolates it. Pre‑defining the loop variable causes the loop to reuse that name, overwriting the global value after the loop.

7. Difference Between + and +=

# Using +
a = [1, 2, 3, 4]
b = a
a = a + [5, 6, 7, 8]
>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4]
# Using +=
a = [1, 2, 3, 4]
b = a
a += [5, 6, 7, 8]
>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4, 5, 6, 7, 8]

Reason: a = a + b creates a new list object and rebinds a, leaving b unchanged. a += b performs an in‑place extend, mutating the original list that both a and b reference.

8. try…finally with return

def some_func():
    try:
        return 'from_try'
    finally:
        return 'from_finally'
>> some_func()
'from_finally'

Reason: In a try…finally block, the finally clause always executes last, and its return overrides any earlier return value.

9. Assigning to True and False

True = False
if True == False:
    print("I've lost faith in truth!")
I've lost faith in truth!

Reason: In early Python versions, True and False were not constants but built‑in variables, allowing reassignment for backward compatibility. Python 3 makes them immutable constants.

10. One‑Step Operations Returning None

some_list = [1, 2, 3]
some_dict = {"key_1": 1, "key_2": 2, "key_3": 3}
some_list = some_list.append(4)
some_dict = some_dict.update({"key_4": 4})
>> print(some_list)
None
>>> print(some_dict)
None

Reason: Methods like list.append and dict.update modify the object in place and return None; assigning their result overwrites the original variable with None.

11. Python for Loop Mechanics

for i in range(4):
    print(i)
    i = 10
0
1
2
3

Reason: The loop variable is reassigned each iteration from the iterator; changing its value inside the loop does not affect the next iteration.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythongeneratordict/looptry-finallyis-operatorelseplus-equalstruth-assignmentvariable-leakage
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

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.