Skip to content

How to fix NoneType in Python

  • by

None denotes that nothing which occurs NoneType error in Python. Use ifis None check rather than try-except to skip if nothing was found

How to fix NoneType in Python

Simple example code ensures that mylist is not None before it is iterated over, which helps avoid the error.

mylist = None

if mylist is not None:
    for x in mylist:
        print(x)
else:
    print("List is None")

Output:

How to fix NoneType in Python

Python TypeError: ‘NoneType’ object is not iterable Solution

A None value is not iterable because it does not contain any objects. One way to avoid this error is to check before iterating on an object if that object is None or not.

def myfunction():
    a_list = [1,2,3]
    a_list.append(4)
    # return a_list

returned_list = myfunction()
if returned_list is None:
    print("returned list is None")
else:
    for item in returned_list:
        # do something with item

In addition, another way to handle this error: Python NoneType object is not iterable is to write the for loop in try-except block.

def myfunction():
    a_list = [1,2,3]
    a_list.append(4)
    return a_list

returned_list = myfunction()
try:
    for item in returned_list:
        # do something with item
except Exception as e:
    # handle the exception accordingly

Thirdly, it is to explicitly assign an empty list to the variable if it is None.

def myfunction():
    a_list = [1,2,3]
    a_list.append(4)
    # return a_list

returned_list = myfunction()
if returned_list is None:
    returned_list = []
for item in returned_list:
    # do something with item

Do comment if you have any doubts or suggestions on this Python question topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *