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
Check out this article - Quicksort Python
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.
Check out Escape Sequence in Python
FAQs
-
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 the following things:
- We first discussed what are TypeErrors and how they occur.
- Then we discussed how to handle TypeErrors.
We hope that this blog has helped you enhance your knowledge regarding TypeErrors in Python language and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!
