Have you ever tried to divide an integer with a string while programming in Python? If yes, you might have got an error message like “TypeError: unsupported operand type(s) for /: ‘int’ and ‘str’”. In this article, we will discuss this TypeError exception in Python. We will also look at different situations when a TypeError exception can occur and how we can avoid them.
What is TypeError in Python?
TypeError is an exception in Python programming language that occurs when the data type of objects in an operation is inappropriate. For example, If you attempt to divide an integer with a string, the data types of the integer and the string object will not be compatible. Due to this, the Python interpreter will raise a TypeError exception as shown in the following example.
myInt = 100
myStr = "10"
myResult = myInt / myStr
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myResult = myInt / myStr
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Let us take another example, Suppose that we want to concatenate two lists. We can do it using the + operator as follows.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
myResult = list1 + list2
print("First list is:", list1)
print("second list is:", list2)
print("Resultant list is:", myResult)
Output:
First list is: [1, 2, 3]
second list is: [4, 5, 6]
Resultant list is: [1, 2, 3, 4, 5, 6]
Now suppose that we pass a tuple in the place of the second list. Here, list and tuple data types are incompatible with each other in a concatenation operator. So, the python interpreter will raise a TypeError exception as shown below.
list1 = [1, 2, 3]
list2 = (4, 5, 6)
myResult = list1 + list2
print("First list is:", list1)
print("second list is:", list2)
print("Resultant list is:", myResult)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myResult = list1 + list2
TypeError: can only concatenate list (not "tuple") to list
Looking at these examples, we can say that TypeError is an exception that is raised by the python interpreter if the data types of different objects in an operation are not compatible and hence inappropriate.
Let us now look at some situations where TypeError exceptions are likely to occur.
When does a TypeError Exception Occur in Python?
Exceptions force the program to terminate prematurely. Also, no one wants exceptions to occur in their programs. But, we cannot control how a user will pass inputs to the program. There can be various situations where TypeError exceptions can occur.
Let’s have a look at some of them.
TypeError Exceptions May Occur While Using In-Built Functions
All the built-in functions accept input arguments of certain types. For example, the add() method in a set accepts only immutable objects like integers, strings, tuples, floating point numbers, etc as input arguments. If we try to give a mutable object like a list as input to the add() method, it will raise TypeError with a message “TypeError: unhashable type: ‘list’ ” as follows.
mySet = {1, 2, 3}
myList = [4, 5, 6]
mySet.add(myList)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
mySet.add(myList)
TypeError: unhashable type: 'list'
TypeError Exceptions May Occur While Performing Operations Between Two Incompatible Data Types
We know that mathematical or bitwise operations are defined only for certain data types in Python. For example, We can add an integer to an integer or a floating-point number. On the other hand, We cannot add a string object to an integer. Adding an integer to a string object will cause TypeError with the message “TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’” as follows.
myInt = 100
myStr = "200"
myResult = myInt + myStr
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myResult = myInt + myStr
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Likewise, all the mathematical operations are allowed only between certain data types. If you try to perform a mathematical operation on objects with incompatible data types, TypeError will occur.
If we talk about bitwise operations, we can perform a bitwise operation on an integer but not on a string. For example, we can right-shift an integer by two bits as follows.
myInt = 100
myResult = myInt >> 2
print("The given Integer is:", myInt)
print("Result is:", myResult)
Output:
The given Integer is: 100
Result is: 25
On the other hand, if we try to perform a right shift operation on a string, it will raise TypeError with the message “TypeError: unsupported operand type(s) for >>: ‘str’ and ‘int’ ” as follows.
myStr = "100"
myResult = myStr >> 2
print("The given String is:", myStr)
print("Result is:", myResult)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
myResult = myStr >> 2
TypeError: unsupported operand type(s) for >>: 'str' and 'int'
So, you can see that performing mathematical or bitwise operations on incompatible data types can cause a TypeError exception in your program.
TypeError Exceptions May Occur While Calling a Non-callable Object
In python, functions, methods, and all the objects with the implementation of __call__() method in their class definition are callable. We can call any callable object as we call a function or a method.
On the other hand, if we call a non-callable object such as an integer, it will raise a TypeError exception with the message “TypeError: ‘int’ object is not callable” as follows.
myInt = 100
myInt()
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
myInt()
TypeError: 'int' object is not callable
How to Avoid TypeError Exceptions in Python?
Errors are inevitable in a program. But, you can always minimize the occurrence of errors. To minimize TypeError exceptions you can use the following guidelines.
- Whenever you are trying to use an in-built method or function, always read its documentation. This will help you understand the inputs and outputs of the functions. Knowledge of the inputs and outputs will help you avoid TypeError exceptions in your program.
- While performing mathematical or bitwise operations, you can check the data types of the operands beforehand. This will help you avoid performing mathematical or bitwise operations on incompatible data types. Hence, you will be able to avoid TypeError exceptions.
- Give proper names to variables, functions, classes, and methods in your programs. This will help you avoid calling a non-callable object. Hence, you will be able to avoid TypeError exceptions.
Conclusion
In this article, we have discussed the TypeError exception, its causes, and how we can avoid them. You can also handle these exceptions using python try-except blocks. But, I will advise you to avoid the exception instead of handling it after it has occurred.
To learn more about python programming, you can read this article on string manipulation in Python. You might also like this article on Python IndexError.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.