Python is beginner-friendly, but even experienced developers make mistakes. Here are 6 common Python mistakes and how to fix them!
1️⃣ Mutating a Default Argument in a Function
❌ Wrong:
def add_item(item, my_list=[]):
my_list.append(item)
return my_list
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] (Unexpected behavior!)
Why? The default list is shared between function calls.
✅ Fix:
def add_item(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
2️⃣ Modifying a List While Iterating
❌ Wrong:
nums = [1, 2, 3, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
✅ Fix (Use List Comprehension Instead!):
nums = [n for n in nums if n % 2 != 0]
3️⃣ Using == Instead of is for None Checks
❌ Wrong:
if my_var == None:
print("None found")
✅ Fix:
if my_var is None:
print("None found")
4️⃣ Confusing = (Assignment) with == (Comparison)
❌ Wrong:
if x = 5: # SyntaxError!
print("x is 5")
✅ Fix:
if x == 5:
print("x is 5")
5️⃣ Not Using enumerate() When Needed
❌ Wrong:
for i in range(len(my_list)):
print(i, my_list[i])
✅ Fix:
for index, value in enumerate(my_list):
print(index, value)
6️⃣ Using + Instead of join() for String Concatenation
❌ Wrong:
words = ["Python", "is", "awesome"]
sentence = ""
for word in words:
sentence += word + " "
✅ Fix:
sentence = " ".join(words)
Which of these mistakes have you made? Let me know in the comments!
Follow for more Python tips!
Top comments (0)