πŸ”§ Error Fixes
Β· 1 min read

Python TypeError β€” How to Fix Common Type Errors


TypeError: 'int' object is not iterable
TypeError: 'NoneType' object is not subscriptable
TypeError: unsupported operand type(s) for +: 'int' and 'str'

You’re using a value in a way that doesn’t match its type. Python is telling you what type it got and what it expected.

Fix 1: Not Iterable

# ❌ Trying to loop over a number
for i in 5:  # πŸ’₯ int is not iterable
    print(i)

# βœ… Use range()
for i in range(5):
    print(i)

Fix 2: Not Subscriptable

# ❌ Indexing into None
result = some_function()  # Returns None
print(result[0])  # πŸ’₯ NoneType is not subscriptable

# βœ… Check for None first
result = some_function()
if result:
    print(result[0])

Fix 3: Unsupported Operand

# ❌ Adding string and int
age = 25
print("Age: " + age)  # πŸ’₯ Can't add str and int

# βœ… Convert to string
print("Age: " + str(age))
# Or use f-string
print(f"Age: {age}")

Fix 4: Not Callable

# ❌ Variable shadows a function name
list = [1, 2, 3]  # Overwrites the built-in list()
new_list = list("hello")  # πŸ’₯ list is now a variable, not a function

# βœ… Don't use built-in names as variables
my_list = [1, 2, 3]

Fix 5: Missing Arguments

# ❌ Forgot self in class method
class User:
    def greet():  # Missing self
        print("Hello")

User().greet()  # πŸ’₯ takes 0 positional arguments but 1 was given

# βœ… Add self
class User:
    def greet(self):
        print("Hello")

Fix 6: Wrong Return Type

# ❌ Function returns None unexpectedly
def get_items():
    items = [1, 2, 3]
    items.sort()  # sort() returns None!

result = get_items()
for item in result:  # πŸ’₯ NoneType is not iterable

# βœ… Return the list explicitly
def get_items():
    items = [1, 2, 3]
    items.sort()
    return items

Related: Pip Install Error Fix

πŸ“˜