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)
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!
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
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])
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()
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.
Very good https://shorturl.at/2breu
Very good https://lc.cx/xjXBQT
Join our affiliate program and start earning commissions todayβsign up now! https://shorturl.fm/GM9o6
Promote our brand and get paidβenroll in our affiliate program! https://shorturl.fm/f6JkF
https://shorturl.fm/qef3V