DEV Community

Cover image for 6 Common Python Mistakes You Should Avoid (And How to Fix Them!)
Thameem Azfar Ansari
Thameem Azfar Ansari

Posted on

6 Common Python Mistakes You Should Avoid (And How to Fix Them!)

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!)
Enter fullscreen mode Exit fullscreen mode

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  
Enter fullscreen mode Exit fullscreen mode

2️⃣ Modifying a List While Iterating
❌ Wrong:

nums = [1, 2, 3, 4]  
for n in nums:  
    if n % 2 == 0:  
        nums.remove(n)  
Enter fullscreen mode Exit fullscreen mode

✅ Fix (Use List Comprehension Instead!):

nums = [n for n in nums if n % 2 != 0] 
Enter fullscreen mode Exit fullscreen mode

3️⃣ Using == Instead of is for None Checks
❌ Wrong:

if my_var == None:  
    print("None found") 
Enter fullscreen mode Exit fullscreen mode

✅ Fix:

if my_var is None:  
    print("None found")  
Enter fullscreen mode Exit fullscreen mode

4️⃣ Confusing = (Assignment) with == (Comparison)
❌ Wrong:

if x = 5:  # SyntaxError!  
    print("x is 5")
Enter fullscreen mode Exit fullscreen mode

✅ Fix:

if x == 5:  
    print("x is 5")
Enter fullscreen mode Exit fullscreen mode

5️⃣ Not Using enumerate() When Needed
❌ Wrong:

for i in range(len(my_list)):  
    print(i, my_list[i])  
Enter fullscreen mode Exit fullscreen mode

✅ Fix:

for index, value in enumerate(my_list):  
    print(index, value)  
Enter fullscreen mode Exit fullscreen mode

6️⃣ Using + Instead of join() for String Concatenation
❌ Wrong:

words = ["Python", "is", "awesome"]  
sentence = ""  
for word in words:  
    sentence += word + " "  
Enter fullscreen mode Exit fullscreen mode

✅ Fix:

sentence = " ".join(words)  
Enter fullscreen mode Exit fullscreen mode

Which of these mistakes have you made? Let me know in the comments!

Follow for more Python tips!

Top comments (0)