Skip to content
Related Articles
Open in App
Not now

Related Articles

Handling TypeError Exception in Python

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 20 Aug, 2020
Improve Article
Save Article

TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise TypeError.


The general causes for TypeError being raised are:

1. Unsupported operation between two types:

In the following example, the variable ‘geek’ is a string and the variable ‘num’ is an integer. The + (addition) operator cannot be used between these two types and hence TypeError is raised.


geek = "Geeks"
num = 4
print(geek + num + geek)

Output :

TypeError: must be str, not int

2. Calling a non-callable identifier:

In the below example code, the variable ‘geek’ is a string and is non-callable in this context. Since it is called in the print statement, TypeError is raised.


geek = "GeeksforGeeks"

Output :

TypeError: 'str' object is not callable

3. Incorrect type of list index:

In Python, list indices must always be an integer value. Since the index value used in the following code is a string, it raises TypeError.


geeky_list = ["geek", "GeeksforGeeks", "geeky", "geekgod"]
index = "1"

Output :

TypeError: list indices must be integers or slices, not str

4. Iterating through a non-iterative identifier:

In the following code, the value 1234.567890 is a floating-point number and hence it is non-iterative. Forcing Python to iterate on a non-iterative identifier will raise TypeError.


for geek in 1234.567890:

Output :

TypeError: 'float' object is not iterable

Handling TypeError

TypeErrors are raised mostly in situations where the programmer fails to check the type of object before performing an operation on them. They can be handled specifically by mentioning them in the except block. In the following example, when one of the indices is found to be an incorrect type, an exception is raised and handled by the program.


geeky_list = ["Geeky", "GeeksforGeeks", "SuperGeek", "Geek"]
indices = [0, 1, "2", 3]
for i in range(len(indices)):
    except TypeError:
        print("TypeError: Check list of indices")

Output :

TypeError: Check list of indices

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!