TypeError Exception in Python

By Lenin Mishra

This is the part of the 9th day in the Python 30 series. Check out the series here.

The TypeError Exception in Python is raised when you try to apply any operation or function call to an inappropriate type of object.

For example - 1. Trying to concatentate a list and a number 2. calling a variable as a function 3. Passing an argument to a function of the wrong type etc.

Example 1

Code/Output

# concatenating list with an integer
x = [1, 2, 3]
y = 2

print(x+y)
>>> TypeError: can only concatenate list (not "int") to list

# passing an unsupported index
x = [1, 2, 3]
print(x[0.5])
>>> TypeError: list indices must be integers or slices, not float

# calling a variable as a function
x = "Pylenin"
x()
>>> TypeError: 'str' object is not callable

# Passing wrong argument
def addition(x, y):
    return x+y

print(addition(10, [1, 2]))
>>> TypeError: unsupported operand type(s) for +: 'int' and 'list'

You can handle these errors using the TypeError Exception class.

Example 2

Code

# concatenating list with an integer
x = [1, 2, 3]
y = 2
try:
    print(x+y)
except TypeError as e:
    print(f"TypeError handled."
          f"Error reason - {e}")

# passing an unsupported index
x = [1, 2, 3]
try:
    print(x[0.5])
except TypeError as e:
    print(f"TypeError handled."
          f"Error reason - {e}")


# calling a variable as a function
x = "Pylenin"
try:
    x()
except TypeError as e:
    print(f"TypeError handled."
          f"Error reason - {e}")


# Passing wrong argument
def addition(x, y):
    return x+y

try:
    print(addition(10, [1, 2]))
except TypeError as e:
    print(f"TypeError handled."
          f"Error reason - {e}")

Output

TypeError handled.Error reason - can only concatenate list (not "int") to list
TypeError handled.Error reason - list indices must be integers or slices, not float
TypeError handled.Error reason - 'str' object is not callable
TypeError handled.Error reason - unsupported operand type(s) for +: 'int' and 'list'

Check out other Python Built-in Exception classes in Python.

  1. Try, Except, Else and Finally in Python
  2. ZeroDivisionError Exception in Python
  3. OverflowError Exception in Python
  4. ArithmeticError Exception in Python
  5. KeyError Exception in Python
  6. IndexError Exception in Python
  7. LookupError Exception in Python
  8. StopIteration Exception in Python
  9. NameError Exception in Python
  10. FileNotFoundError Exception in Python
  11. Catch Multiple Exceptions in Python