Calling a non-callable object or function
If we call a non-callable object then a TypeError exception occurs. For example, calling an integer value will give an error.
Code
value = 12
value()
Output
TypeError: 'int' object is not callable
Incorrect type of lists index
The list indices should be integer only. If we access them with a character, string, float, etc. then we will get the TypeError exception.
Code
values = [1, 2, 3, 4, 5]
print(values['1'])
Output
TypeError: list indices must be integers or slices, not str
Recommended Topic, Divmod in Python
Iterating a non-iterative object
If we try to iterate a non-iterative object, then also we will get the TypeError exception. For example, iterating an integer value.
Code
values = [1, 2, 3, 4, 5]
print(values['1'])
Output
TypeError: 'int' object is not iterable
Handling TypeErrors
We can handle the TypeError using the ‘try’ and ‘except’ blocks. We can explicitly mention it in the except block.
Code
list = ["Coding", "Ninjas", "CodingNinjas"]
indices = [0, 1, "2"]
for i in range(len(indices)):
try:
print(list[indices[i]])
except TypeError:
print("TypeError: Check list of indices")
Output
Coding
Ninjas
TypeError: Check list of indices
You can try it on online python compiler.
Frequently Asked Questions
What is a TypeError?
TypeError is one of the Exceptions in Python. Whenever we make a call or access any object which does not exist or is unsupported then the TypeError exception occurs.
How do we handle TypeErrors?
We can handle the TypeError using the ‘try’ and ‘except’ blocks. We can explicitly mention TypeError in the except block.
Conclusion
In this article, we have extensively discussed TypeErrors, starting with what they are and the situations in which they occur. We then explored different ways to handle TypeErrors effectively, ensuring smoother and error-free program execution.
Recommended Readings: