10 Common Python Mistakes and How to Fix Them
Learn the most common Python mistakes beginners make and how to avoid them. Improve your coding skills with practical examples.
10 Common Python Mistakes and How to Fix Them
1. Mutable Default Arguments
```python
def append_item(item, lst=[]):
lst.append(item)
return lst
print(append_item(1)) # [1]
print(append_item(2)) # [1, 2] - Oops!
```
```python
def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
```
2. Forgetting Colons in Control Structures
```python
if x > 5
print("x is large")
```
```python
if x > 5:
print("x is large")
```
3. Confusion Between = and ==
```python
if x = 5: # SyntaxError
print(x)
```
```python
if x == 5:
print(x)
```
4. Off-by-One Errors with range()
```python
for i in range(1, 5): # Goes 1, 2, 3, 4 (not 5)
print(i)
```
5. Modifying Lists While Iterating
```python
nums = [1, 2, 3, 4, 5]
for num in nums:
if num % 2 == 0:
nums.remove(num) # Skips elements!
```
```python
nums = [1, 2, 3, 4, 5]
nums = [n for n in nums if n % 2 != 0]
```
6. Confusing None with False
```python
if not value: # Treats None, False, 0, "" the same
print("empty")
```
```python
if value is None:
print("value is None")
```
7. Shadowing Built-ins
```python
list = [1, 2, 3] # Now list() function is gone!
new_list = list() # TypeError
```
```python
my_list = [1, 2, 3]
```
8. Index Out of Range
```python
lst = [1, 2, 3]
print(lst[5]) # IndexError
```
```python
lst = [1, 2, 3]
if len(lst) > 5:
print(lst[5])
Or use get() for dicts
```
9. Forgetting Global Keyword
```python
x = 10
def change_x():
x = 20 # Creates local variable, doesn''t change global
change_x()
print(x) # 10
```
```python
x = 10
def change_x():
global x
x = 20
change_x()
print(x) # 20
```
10. String Concatenation in Loops
```python
result = ""
for i in range(1000):
result += str(i) # Slow! Creates new string each time
```
```python
result = "".join(str(i) for i in range(1000))
```
Summary
Avoid these mistakes by:
- Using linters (pylint, flake8)
- Writing tests
- Code reviews
- Practice on PythonExecutor!
By PythonExecutor Team