10 Common Python Pitfalls Every Developer Should Avoid
This article defines what constitutes a Python trap and walks through ten classic pitfalls—including mutable default arguments, the subtle differences between x+=y and x=x+y, tuple syntax quirks, list-of-lists initialization, modifying lists during iteration, late-binding closures, __del__ garbage‑collection issues, import inconsistencies, Python 2‑to‑3 changes, and the infamous GIL—providing clear examples and best‑practice solutions.
My personal definition of a trap is code that appears to work but not in the way you "assume"; an error that raises an exception directly is not a trap. For many Python beginners, errors like UnboundLocalError can be confusing, but they are not traps because they always raise an exception.
1. Using mutable objects as default arguments
When a mutable object (e.g., a list) is used as a default parameter, the default is evaluated only once at function definition time, causing unexpected shared state across calls.
def f(lst=[]):
lst.append(1)
return lst
print(f()) # [1]
print(f()) # [1, 1] <-- unexpectedThe Python documentation recommends using None as the default and initializing inside the function body.
def f(lst=None):
if lst is None:
lst = []
lst.append(1)
return lst2. x += y vs x = x + y
These statements look equivalent but behave differently for mutable objects because += modifies the object in place, while = creates a new object.
x = 1
x += 1
print(x) # 2
x = [1]
x += [2]
print(x) # [1, 2] (in‑place)3. The magic of parentheses ()
Parentheses create tuples, which are immutable sequences. A single‑element tuple requires a trailing comma.
a = (1, 2)
print(type(a)) # <class 'tuple'>
# Single element
b = (1,)
print(type(b)) # <class 'tuple'>4. Creating a list of lists
Using multiplication on a mutable list creates references to the same inner list, leading to unexpected shared modifications.
a = [[]] * 10 # all inner lists are the same object
a[0].append(1)
print(a) # [[1], [1], ..., [1]]The correct approach is to use a list comprehension:
a = [[] for _ in range(10)]5. Modifying a list while iterating over it
Removing elements from a list during iteration can skip items because the index continues to increase while the list shrinks.
def modify_lst(lst):
for idx, elem in enumerate(lst):
if elem % 3 == 0:
del lst[idx]A safer alternative is to build a new list with a comprehension.
6. Closures and lambda
Python closures use late binding, so variables captured by a lambda are looked up when the inner function is called, not when it is defined.
def create_multipliers():
return [lambda x: i * x for i in range(5)]
for m in create_multipliers():
print(m(2)) # prints 8 five timesFix by binding the current value as a default argument:
def create_multipliers():
return [lambda x, i=i: i * x for i in range(5)]7. Defining __del__
Objects with a __del__ method participating in reference cycles cannot be collected by the garbage collector, potentially causing memory leaks.
8. Importing the same module in different ways
Using different import statements (e.g., import mymodule vs from mypackage import mymodule) can load separate module objects with different id s, leading to inconsistent state.
9. Python version upgrades
Python 2 and Python 3 differ in the return types of range, map, filter, and dict.items(); the former return lists, while the latter return iterators, which can cause subtle bugs when code expects a list.
10. The Global Interpreter Lock (GIL)
The GIL is a well‑known limitation of CPython that prevents true parallel execution of Python bytecode in multiple threads, often surprising developers coming from languages without such a lock.
Understanding these traps helps Python developers write more reliable and maintainable code.
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.
