Lesson 17 of 19 · 2 min
Common Mistakes and Their Exact Error Messages
Mistake 1 — IndexError: Going Past the End of a List
fruits = ["apple", "banana", "mango"] # valid indexes: 0, 1, 2 print(fruits[3]) # index 3 does not exist!
IndexError: list index out of range
Fix: Check len(fruits) > 3 before accessing index 3, or use fruits[-1] for the last item.
Mistake 2 — KeyError: Accessing a Missing Dictionary Key
student = {"name": "Priya", "age": 20}
print(student["cgpa"]) # "cgpa" key was never added
KeyError: 'cgpa'
Fix: Use student.get("cgpa") (returns None) or student.get("cgpa", 0.0) (returns default 0.0).
Mistake 3 — TypeError: Trying to Modify a Tuple
coords = (10, 20, 30) coords[0] = 99 # tuples do not support item assignment
TypeError: 'tuple' object does not support item assignment
Fix: Use a list [10, 20, 30] if you need mutability.
Mistake 4 — AttributeError: Using {} for an Empty Set
my_set = {} # THIS creates an empty DICTIONARY, not a set!
my_set.add(1) # dictionaries have no add() method
AttributeError: 'dict' object has no attribute 'add'
Fix: Use my_set = set() to create an empty set.
Mistake 5 — UnboundLocalError: Forgetting global Keyword
counter = 0
def increment():
counter += 1 # Python sees assignment → treats counter as LOCAL → error
print(counter)
increment()
UnboundLocalError: local variable 'counter' referenced before assignment
Fix: Add global counter as the first line inside increment().
Mistake 6 — Single-Item Tuple Missing the Comma
x = (42) # just integer 42 in parentheses — NOT a tuple! print(type(x)) # <class 'int'> — surprise! y = (42,) # the trailing comma makes it a tuple print(type(y)) # <class 'tuple'>
Output: <class 'int'> <class 'tuple'>
Mistake 7 — Reference vs Copy
original = [1, 2, 3] alias = original # NOT a copy — both point to the SAME list alias.append(99) # modifying alias also modifies original! print(original) # [1, 2, 3, 99] — unexpected change! proper_copy = original.copy() # independent copy proper_copy.append(100) print(original) # [1, 2, 3, 99] — original unaffected
Output: [1, 2, 3, 99] [1, 2, 3, 99]
