🐍 Common Python Coding Mistakes

1. ❌ Using Mutable Default Arguments

def add_item(item, item_list=[]):
item_list.append(item)
return item_list
  • Problem: item_list retains values across multiple calls.
  • Fix:
def add_item(item, item_list=None):
if item_list is None:
item_list = []
item_list.append(item)
return item_list

2. ❌ Not Using List Comprehensions When Appropriate

squared = []
for i in range(10):
squared.append(i ** 2)
  • Better:
squared = [i ** 2 for i in range(10)]

3. ❌ Misunderstanding is vs ==

a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False
print(a == b) # True
  • Use == for value comparison, is for identity comparison (same object in memory).

4. ❌ Importing Everything from a Module

from math import *
  • Problem: Clutters namespace, risk of name collisions.
  • Fix:
import math
print(math.sqrt(9))

5. ❌ Ignoring Exceptions or Catching Broad Exceptions

try:
risky_operation()
except Exception:
pass # Silent fail – bad practice!
  • Fix:
try:
risky_operation()
except ValueError as e:
print(f"Value error: {e}")

6. ❌ Not Using Virtual Environments

  • Leads to dependency conflicts.
  • Fix:
python -m venv venv
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows

7. ❌ Using print() for Debugging in Production Code

  • Use the logging module instead:
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")

8. ❌ Misusing Global Variables

counter = 0

def increment():
counter += 1 # Error: UnboundLocalError
  • Fix:
def increment():
global counter
counter += 1

9. ❌ Overcomplicating with Loops When You Can Use map, filter, or zip

names = ['Alice', 'Bob']
ages = [24, 27]
for i in range(len(names)):
print(names[i], ages[i])
  • Better:
for name, age in zip(names, ages):
print(name, age)

10. ❌ Forgetting to Close Files (Before Using Context Manager)

file = open('data.txt')
data = file.read()
file.close()
  • Fix (Recommended):
with open('data.txt') as file:
data = file.read()

✅ Bonus Tips

  • Use type hints for better readability and tooling:
def add(x: int, y: int) -> int:
return x + y
  • Use tools like Black, Flake8, and Pylint to format and lint your code.
  • Write unit tests using unittest or pytest.

Leave a Reply

Your email address will not be published. Required fields are marked *