10 Common Python Pitfalls and How to Avoid Them
This article walks through ten frequent Python gotchas—from mutable default arguments and for‑else usage to dictionary key hashing, proper if checks, lazy‑evaluation closures, path handling, eval quirks, while loop nuances, multiline strings, and requests encoding—providing clear explanations and corrected code examples.
1. Avoid mutable default arguments
Using a list as a default parameter makes it act like a global variable, causing unexpected accumulation across calls.
def foo(num, age=[]):
age.append(num)
print("num", num)
return age
print(foo(1))
print(foo(2))
print(foo(3))The above prints:
num 1
[1]
num 2
[1, 2]
num 3
[1, 2, 3]Fix by using None as the default and creating a new list inside the function.
def foo(num, age=None):
if not age:
age = []
age.append(num)
print("num", num)
return age
print(foo(1))
print(foo(2))
print(foo(3))2. Using for‑else to find primes
The for‑else construct runs the else block only when the loop completes without a break, which is handy for prime detection.
# find primes up to 100
import math
num = []
for i in range(2, 100):
for j in range(2, int(math.sqrt(i)) + 1):
if i % j == 0:
break
else:
num.append(i)
for index, i in enumerate(num):
if index == len(num) - 1:
print(i)
else:
print(i, end=" ")This demonstrates why the final else is essential for correctly identifying primes.
3. Dictionary key hashing quirks
Dictionary keys are compared by equality and hash value; 1 and 1.0 share the same hash, so the later assignment overwrites the former.
a = {}
a[1] = "A"
a[1.0] = "B"
a[2] = "C"
print(a)Result: {1: 'B', 2: 'C'} Hashes of immutable objects with the same value are equal, e.g.:
hash(1) == hash(1.0) == hash(True)
hash(0) == hash(False) == hash("")4. Proper if‑condition checks
In Python, empty containers evaluate to False, so if not a: is preferred over a == None.
a = []
b = {}
c = ""
if not a:
print("a not empty")
if not b:
print("b not empty")
if not c:
print("c not empty")For many branches, a dispatch dictionary is cleaner:
my_dict = {"A": 1, "B": 2}
print(my_dict[type])When initializing many attributes from a dict, use self.__dict__.update(dicts):
class A():
def __init__(self, dicts):
self.__dict__.update(dicts)
print(self.__dict__)
if __name__ == '__main__':
dicts = {"name": "lisa", "age": 23, "sex": "women", "hobby": "hardstyle"}
a = A(dicts)5. Closure lazy‑evaluation trap
Lambda functions capture variables by reference, so all lambdas see the final loop value.
ls = []
for x in range(5):
ls.append(lambda: x**2)
print(ls[0]())
print(ls[1]())
print(ls[2]())All three calls output 16 because x is 4 after the loop ends.
6. File path vs current working directory
Use os.getcwd() for the current working directory and sys.path[0] for the script’s directory.
import os
os.getcwd()
import sys
sys.path[0]7. eval cannot parse numbers with a leading zero
eval("02")This raises SyntaxError: invalid token because leading zeros are not allowed in numeric literals.
8. while 1 vs while True
In Python 2, True could be reassigned, making while 1 slightly faster; in Python 3, True is a keyword, so both loops behave identically.
9. Handling long multiline strings
Wrap a triple‑quoted string in parentheses to avoid accidental line‑break issues:
("""multi line text""")10. requests encoding shortcut
Set the response encoding to the detected one with a single line:
res.encoding = res.apparent_encodingSigned-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.
