Python reads like pseudocode, so beginners assume it behaves like pseudocode. It doesn’t. Mutable objects, scope rules, and identity checks all have behavior that surprises newcomers and produces bugs that pass without errors. This guide covers the ten mistakes that appear most often in beginner code, with the exact output each one produces and the fix. All examples target Python 3.10+.
Quick Takeaways
- Mutable default arguments (
def f(x=[])) share state across calls. Default toNoneinstead. - Use
==to compare values andisonly forNone,True, andFalse. - Never modify a list while iterating over it. Build a new list with a list comprehension.
- Catch specific exceptions. A bare
except:hides real bugs and swallowsKeyboardInterrupt.
| Mistake | Symptom | Fix |
|---|---|---|
| Mutable default argument | Data leaks between calls | param=None |
is for value comparison |
Inconsistent False results |
== |
| Mutating a list mid-loop | Skipped elements | List comprehension |
Bare except |
Silent failures | except ValueError |
| Shadowing built-ins | TypeError: not callable |
Rename variables |
| Aliasing instead of copying | Original data changes | .copy() / deepcopy() |
Mistake 1: Mutable Default Arguments
Python evaluates default values once, when the function is defined, not each time it is called. A mutable default like a list or dict becomes shared state.
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("python")) # ['python']
print(add_tag("rust")) # ['python', 'rust'] <-- unexpected
The second call returns both tags because both calls mutate the same list object. The fix is to use None as a sentinel and create the list inside the function body.
def add_tag(tag, tags=None):
if tags is None:
tags = [] # fresh list on every call
tags.append(tag)
return tags
print(add_tag("python")) # ['python']
print(add_tag("rust")) # ['rust']
Each call now gets its own list. The same rule applies to dict, set, and any custom mutable object.
Mistake 2: Confusing is with ==
The == operator compares values. The is operator compares object identity, meaning whether two names point at the same object in memory.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (same contents)
print(a is b) # False (two separate objects)
Small integers and some strings are cached by CPython, so is sometimes appears to work. That behavior is an implementation detail. It breaks without warning on larger values, and Python 3.8+ raises a SyntaxWarning when you compare to a literal with is.
| Operator | Compares | Use for |
|---|---|---|
== |
Value equality | Numbers, strings, lists, dicts |
is |
Object identity | None, True, False, sentinels |
The correct None check looks like this:
result = None
if result is None:
print("No result yet")
The singleton None has exactly one instance, so is None is both correct and idiomatic.
Mistake 3: Modifying a List While Iterating
Removing items from a list inside a for loop shifts the indices under the iterator. The loop then skips elements.
numbers = [2, 4, 6, 8, 1]
for n in numbers:
if n % 2 == 0:
numbers.remove(n)
print(numbers) # [4, 8, 1] <-- 4 and 8 survived
After each removal, the remaining items slide left, and the iterator moves right past them. Build a new list instead.
numbers = [2, 4, 6, 8, 1]
odds = [n for n in numbers if n % 2 != 0]
print(odds) # [1]
The list comprehension runs in O(n) time and never touches the list it reads from. If you must mutate in place, iterate over a copy with for n in numbers[:].
Mistake 4: Using a Bare except Clause
A bare except: catches everything, including KeyboardInterrupt and SystemExit. Your program becomes impossible to stop with Ctrl+C, and real bugs vanish without a trace.
user_input = "abc"
try:
value = int(user_input)
except:
pass # swallows every error, including typos in your own code
Catch the specific exception you expect and decide what happens next.
def parse_int(raw: str) -> int | None:
"""Return the integer value of raw, or None if it is not numeric."""
try:
return int(raw)
except ValueError:
return None
print(parse_int("42")) # 42
print(parse_int("abc")) # None
Now a ValueError is handled deliberately, and any other exception still surfaces with a full traceback.
Mistake 5: Shadowing Built-in Names
Python lets you reassign names like list, str, sum, max, id, and type. Doing so hides the built-in for the rest of that scope.
list = [1, 2, 3] # overwrites the built-in list type
numbers = list((4, 5, 6))
# TypeError: 'list' object is not callable
The error appears far from the cause, which makes it painful to debug. Pick descriptive names instead.
items = [1, 2, 3]
numbers = list((4, 5, 6))
print(numbers) # [4, 5, 6]
Linters such as Ruff and Pylint flag shadowed built-ins automatically. Turn them on in your editor.
Mistake 6: Aliasing Instead of Copying
Assignment in Python never copies an object. It binds a second name to the same object.
original = [1, 2, 3]
alias = original
alias.append(4)
print(original) # [1, 2, 3, 4] <-- original changed
Use .copy(), list(), or slicing for a shallow copy. Use copy.deepcopy() when the list contains other mutable objects.
import copy
original = [[1, 2], [3, 4]]
shallow = original.copy()
deep = copy.deepcopy(original)
original[0].append(99)
print(shallow) # [[1, 2, 99], [3, 4]] <-- inner list is shared
print(deep) # [[1, 2], [3, 4]] <-- fully independent
| Method | Copies outer container | Copies nested objects | Cost |
|---|---|---|---|
b = a |
No | No | O(1) |
a.copy() |
Yes | No | O(n) |
copy.deepcopy(a) |
Yes | Yes | O(n) over all nested items |
The Nested List Trap
The same aliasing problem appears when beginners build a 2D grid with multiplication.
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
The outer * repeats a reference to one inner list three times. Use a comprehension so each row is a distinct object.
grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Mistake 7: Expecting In-Place Methods to Return a Value
Methods that mutate a list in place, such as .sort(), .append(), and .reverse(), return None. Assigning their result is a classic trap.
scores = [3, 1, 2]
result = scores.sort()
print(result) # None
print(scores) # [1, 2, 3]
If you need a new sorted list and want to keep the original, use the built-in sorted() function.
scores = [3, 1, 2]
ranked = sorted(scores, reverse=True)
print(ranked) # [3, 2, 1]
print(scores) # [3, 1, 2] (unchanged)
The rule of thumb: methods that change an object return None. Functions that build something new return the new object.
Mistake 8: Misunderstanding Variable Scope
Assigning to a name inside a function makes that name local for the entire function. Reading it before assignment raises an error.
count = 0
def increment():
count += 1 # UnboundLocalError
increment()
Python sees the assignment in count += 1, treats count as local, and finds no value for it. The global keyword fixes this, but it makes code harder to test. Pass state in and return the result instead.
def increment(count: int) -> int:
return count + 1
count = 0
count = increment(count)
print(count) # 1
Pure functions like this one are easier to test and reason about. Reserve global for rare configuration cases.
Mistake 9: Comparing Floats for Exact Equality
Floating-point numbers use binary representation, so many decimal values cannot be stored exactly.
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
Compare floats within a tolerance using math.isclose(). For money, use the decimal module.
import math
from decimal import Decimal
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # True
Build Decimal values from strings, not floats. Decimal(0.1) inherits the float’s imprecision.
Mistake 10: Sloppy File Handling and Missing Virtual Environments
Two habits separate scripts that survive from scripts that rot.
First, open files with a context manager. A manual open() without close() leaks file handles, especially when an exception fires between the two calls.
from pathlib import Path
# Context manager closes the file even if an error occurs
with open("data.txt", encoding="utf-8") as f:
content = f.read()
# Shorter for small files
content = Path("data.txt").read_text(encoding="utf-8")
Always pass encoding="utf-8" explicitly. The default depends on the operating system and causes cross-platform bugs.
Second, isolate every project in a virtual environment. Installing packages globally leads to version conflicts between projects.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install requests
pip freeze > requirements.txt
Each project now carries its own dependencies, and requirements.txt makes the setup reproducible on another machine.
Bad Code vs. Good Code: A Full Refactor
This function combines several mistakes from this guide: a mutable default, range(len()), an != None comparison, and a bare except.
Anti-pattern:
def process(data, results=[]):
for i in range(len(data)):
try:
if data[i] != None:
results.append(int(data[i]))
except:
pass
return results
print(process(["1", "2", None])) # [1, 2]
print(process(["3"])) # [1, 2, 3] <-- state leaked
The second call returns values from the first. Every non-numeric string also disappears without a trace.
Refactored:
def parse_ints(data: list[str | None]) -> list[int]:
"""Convert numeric strings to integers, skipping None and invalid values."""
results: list[int] = []
for raw in data:
if raw is None:
continue
try:
results.append(int(raw))
except ValueError:
continue # skip non-numeric strings intentionally
return results
print(parse_ints(["1", "2", None])) # [1, 2]
print(parse_ints(["3"])) # [3]
Changes made:
| Before | After | Why |
|---|---|---|
results=[] |
Local results list |
No shared state |
range(len(data)) |
for raw in data |
Direct iteration, less noise |
!= None |
is None |
Identity check for singletons |
except: |
except ValueError |
Targeted error handling |
| No types | Type hints | Self-documenting, tool-friendly |
If you also need the index, use enumerate() rather than range(len()).
Quick Debugging Habits That Prevent These Bugs
- Read the traceback bottom-up. The last line names the exception, and the lines above it show the call path.
- Print types and identity with
type(x)andid(x)when an object behaves unexpectedly. - Run a linter. Ruff catches most of the mistakes above before you run the code.
- Add type hints and run mypy or Pyright to expose wrong assumptions early.
- Write one test per bug. A
pytestcase keeps a fixed bug from returning.
Frequently Asked Questions
What is the most common mistake beginners make in Python?
Mutable default arguments cause the most confusing bugs, because the code runs without errors and returns wrong data. Indentation errors and misusing is instead of == follow closely behind.
What is the difference between is and == in Python?
== checks whether two objects have equal values. is checks whether two names refer to the exact same object in memory. Use == for values and is only for None, True, and False.
How do I fix IndentationError in Python?
Use 4 spaces per indentation level and never mix tabs with spaces. Configure your editor to insert spaces when you press Tab, and run a formatter such as Black or Ruff to normalize the whole file.
Why does Python say “‘list’ object is not callable”?
You assigned a value to the name list, which hides the built-in list() constructor. Rename your variable (for example, to items) and restart your interpreter session so the old binding is cleared.




