error python

Python TypeError

Understanding Python TypeError - raised when an operation or function is applied to an object of inappropriate type.

What It Means

TypeError is raised when an operation or function receives an argument of the wrong type. Python is dynamically typed, so these errors occur at runtime when you try to use a value in a way that’s incompatible with its type.

Common Causes

  • Adding/concatenating incompatible types (e.g., string + integer)
  • Calling a non-callable object (e.g., None() or int())
  • Passing wrong number of arguments to a function
  • Using a non-iterable where an iterable is expected
  • Subscripting a non-subscriptable object (e.g., int[0])
  • Missing self parameter in class methods
  • Passing None where an object is expected

How to Fix

Fix type concatenation errors

# Error: TypeError: can only concatenate str (not "int") to str
name = "Age: " + 30

# Fix: convert to the same type
name = "Age: " + str(30)
# Or use f-strings
name = f"Age: {30}"

Fix “not callable” errors

# Error: TypeError: 'int' object is not callable
result = 42
result()  # Trying to call an integer

# Common cause: variable name shadowing a function
list = [1, 2, 3]       # Shadows the built-in list()
new_list = list("abc")  # TypeError: 'list' object is not callable

# Fix: don't shadow built-in names
my_list = [1, 2, 3]
new_list = list("abc")  # Works

Fix argument count errors

# Error: TypeError: func() takes 2 positional arguments but 3 were given

# Common cause: forgetting 'self' in class methods
class MyClass:
    def greet(name):      # Missing self!
        print(f"Hi {name}")

# Fix: add self
class MyClass:
    def greet(self, name):
        print(f"Hi {name}")

Fix “not subscriptable” errors

# Error: TypeError: 'NoneType' object is not subscriptable
result = some_function()  # Returns None
value = result[0]         # Can't index None

# Fix: check for None
result = some_function()
if result is not None:
    value = result[0]

Fix “not iterable” errors

# Error: TypeError: 'int' object is not iterable
for item in 42:
    print(item)

# Fix: ensure you're iterating over a collection
for item in [42]:
    print(item)

# Common in unpacking
# Error: TypeError: cannot unpack non-iterable NoneType object
x, y = None  # Function returned None instead of a tuple

# Fix: check return value
result = get_coordinates()
if result:
    x, y = result

Fix unsupported operand errors

# Error: TypeError: unsupported operand type(s) for +: 'int' and 'str'
total = 5 + "10"

# Fix: convert types
total = 5 + int("10")  # 15
# or
total = str(5) + "10"  # "510"

Type checking

# Use isinstance() to check types before operations
def process(data):
    if isinstance(data, str):
        return data.upper()
    elif isinstance(data, (int, float)):
        return data * 2
    else:
        raise TypeError(f"Expected str or number, got {type(data).__name__}")