7 Common Python Pitfalls Explained with Code Examples
This article walks through seven tricky Python snippets—default mutable arguments, lambda closures, class variable inheritance, division differences between Python 2 and 3, out‑of‑range slicing, list multiplication side effects, selective list comprehensions, and custom dict subclasses—explaining their outputs and how to fix them.
1. Mutable default argument pitfall
The function
def extendList(val, list=[]):
list.append(val)
return listshares the same default list across calls, producing list1 = [10, 'a'], list2 = [123], and list3 = [10, 'a']. The fix is to use list=None and create a new list inside the function:
def extendList(val, list=None):
if list is None:
list = []
list.append(val)
return listNow the calls yield list1 = [10], list2 = [123], list3 = ['a'].
2. Lambda closure and late binding
The function
def multipliers():
return [lambda x: i * x for i in range(4)]returns four lambdas that all capture the final value of i (3), so print([m(2) for m in multipliers()]) outputs [6, 6, 6, 6]. Solutions include:
Using a generator:
def multipliers():
for i in range(4):
yield lambda x: i * xBinding the current value as a default argument:
def multipliers():
return [lambda x, i=i: i * x for i in range(4)]Using functools.partial:
from functools import partial
from operator import mul
def multipliers():
return [partial(mul, i) for i in range(4)]3. Class variable inheritance
Given
class Parent(object):
x = 1
class Child1(Parent):
pass
class Child2(Parent):
pass
print(Parent.x, Child1.x, Child2.x)
Child1.x = 2
print(Parent.x, Child1.x, Child2.x)
Parent.x = 3
print(Parent.x, Child1.x, Child2.x)the output is:
1 1 1
1 2 1
3 2 3The first print shows the inherited value. Assigning to Child1.x creates a separate attribute for that subclass only. Changing Parent.x later affects subclasses that have not overridden the attribute (e.g., Child2).
4. Division in Python 2 vs Python 3
In Python 2, / performs integer division when both operands are integers, while // always performs floor division. The sample code prints:
5/2 = 2
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0In Python 3, / always returns a float, so the first two lines become 5/2 = 2.5 and 5.0/2 = 2.5. The // operator still performs floor division.
5. Out‑of‑range list slicing
Accessing a slice with a start index beyond the list length returns an empty list without raising IndexError:
list = ['a', 'b', 'c', 'd', 'e']
print(list[10:]) # []Direct indexing like list[10] would raise an error, but slicing is safe.
6. List multiplication and shared references
Creating a list of lists with list = [[]] * 5 produces five references to the same inner list. Appending to one element updates all references:
list[0].append(10)
# [[10], [10], [10], [10], [10]]
list[1].append(20)
# [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20]]
list.append(30)
# [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30]The lesson is to create independent inner lists, e.g., list = [ [] for _ in range(5) ].
7. Filtering even values at even indices
Using a single list comprehension to select even numbers that appear at even positions (0‑based) can be written as: [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. Custom dict subclass with __missing__
A subclass defining def __missing__(self, key): return [] allows missing keys to return an empty list instead of raising KeyError. The following runs without error:
class DefaultDict(dict):
def __missing__(self, key):
return []
d = DefaultDict()
d['florp'] = 127When a key is absent, __missing__ provides the default value.
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.
