Common Python Gotchas: Default Arguments, Closures, Class Variables & Division Explained
This article walks through several puzzling Python code snippets, explaining why default mutable arguments share state, how closures suffer from late binding, the inheritance of class variables, differences in division between Python 2 and 3, list slicing quirks, and how list multiplication creates shared references, while also offering corrected implementations.
1. Output of extendList and how to modify it
The original extendList uses a mutable default argument ( []) which is created only once when the function is defined, causing list1 and list3 to share the same list. The output is list1 = [10, 'a'], list2 = [123], list3 = [10, 'a']. To get independent lists, set the default to None and create a new list inside the function.
def extendList(val, lst=None):
if lst is None:
lst = []
lst.append(val)
return lstWith this change the result becomes list1 = [10], list2 = [123], list3 = ['a'].
2. Multipliers closure issue
The original multipliers returns a list of lambdas that capture the loop variable i. Because of Python’s late binding, all lambdas see the final value of i (3), so calling them with x = 2 yields [6, 6, 6, 6] instead of the expected [0, 2, 4, 6]. Solutions include using a generator, binding the current value of i as a default argument, or using functools.partial.
def multipliers():
return [lambda x, i=i: i * x for i in range(4)]Now m = multipliers(); [m_i(2) for m_i in m] produces [0, 2, 4, 6].
3. Class variable inheritance
Class variables are stored in the class’s dictionary. Accessing Parent.x finds the value in the parent class; if a subclass overrides it, the subclass sees its own value. The three print statements illustrate this: first all classes see x = 1, after Child1.x = 2 the output is 1 2 1, and after Parent.x = 3 the output becomes 3 2 3.
4. Division in Python 2 vs Python 3
In Python 2, the / operator performs integer division when both operands are integers, so 5/2 yields 2. With a float operand, true division occurs ( 5.0/2 = 2.5). The floor‑division operator // always truncates toward negative infinity. In Python 3, / always performs true division, so 5/2 = 2.5. The examples:
def div1(x, y):
print("%s/%s = %s" % (x, y, x / y))
def div2(x, y):
print("%s//%s = %s" % (x, y, x // y))Python 2 output: 5/2 = 2, 5.0/2 = 2.5, 5//2 = 2, 5.0//2 = 2.0. Python 3 output: 5/2 = 2.5, 5.0/2 = 2.5, 5//2 = 2, 5.0//2 = 2.0.
5. List slicing vs IndexError
Accessing an out‑of‑range index (e.g., list[10]) raises IndexError. However, slicing with a start index beyond the list length simply returns an empty list, which can be a source of subtle bugs.
6. List multiplication reference issue
The expression [[]] * 5 creates a list containing five references to the *same* inner list. Appending to one inner list appears to modify all of them:
lst = [[]] * 5
lst[0].append(10) # results in [[10], [10], [10], [10], [10]]To obtain independent inner lists, use a list comprehension:
lst = [[] for _ in range(5)]
lst[0].append(10)
lst[1].append(20)
lst.append(30)
# Result: [[10], [20], [], [], [], 30]7. List comprehension filtering even‑indexed even numbers
To create a new list containing only even numbers that appear at even positions in the original list, use a single list comprehension:
new_list = [x for x in lst[::2] if x % 2 == 0]For lst = [1,3,5,8,10,13,18,36,78] the result is [10, 18, 78].
8. DefaultDict example
A custom DefaultDict subclass returns an empty list for missing keys via the __missing__ method. The code runs without error:
class DefaultDict(dict):
def __missing__(self, key):
return []
d = DefaultDict()
d['florp'] = 127Accessing d['missing'] would yield [].
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
