How To Solve “TypeError: Cannot Unpack Non-iterable NoneType Object” in Python 

TypeError: cannot unpack non-iterable NoneType object

If you are facing the “TypeError: Cannot Unpack Non-iterable NoneType Object” error in Python, we have effective solutions for you to apply. Follow the article below.

Why does the “Cannot Unpack Non-iterable NoneType Object” error in Python happen?

This error occurs when you unpack values ​​that have no return value, or you fix to a nullable object for each variable in a function.

So that you can solve the problem quickly before it runs out, I have a few definitions for you: TypeError, NoneType, Unpacking.

TypeError: The ‘TypeError‘ occurs when the data types are incompatible with the same function.

NoneType: ‘NoneType’ is a data type representing an object with no value.

What is Unpacking ?

I have an example:

numbers = [1, 2, 3] 

As you can see, I packed the values ​​1 2 3 into a variable named “number”.

To output the above code to the screen, we need to assign each variable “numbers” value to a separate variable.

Example:

numbers = [1, 2, 3] 
p, d, f = numbers

print(p)
print(d)
print(f)

Output:

1
2
3

Hopefully, through the above example, you have understood what Unpacking is.

Example:

ages = [23, 45, 50]
s, m, f = ages.sort()
ages = ages.sort()

print('Sister: ', s)
print('Mother: ', m)
print('Father: ', f)

Output:

TypeError: cannot unpack non-iterable NoneType object

The cause of this error is the sort() method din’t use correctly before unpacking.

How to fix this error?

Make sure you don’t assign the ‘NoneType’ to the values ​​of the ‘ages’ variable

Because we use the sort() method, which returns ‘NoneType,’ we’ll get ‘TypeErrror’. Here’s how to fix it:

Example:

ages = [23, 45, 50]
s, m, f = ages
ages = ages.sort()

print('Sister: ', s)
print('Mother: ', m)
print('Father: ', f)

Output:

Sister:  23
Mother:  45
Father:  50

NOTE: The sort() method will sort the value of the variable “ages” in increasing order.

Make sure the function has an exact return statement.

If there isn’t a statement that returns correctly, it also results in an error “TypeError: cannot unpack non-iterable NoneType object.” 

EXAMPLE:

def nbFunction(c, d):
    return c

z, y = nbFunction(23, 34)

print(z)
print(y)

Output:

TypeError: cannot unpack non-iterable int object

The program crashes because the value ‘d’ is missing from the function.

Correct code:

def nbFunction(c, d):
	return c, d

z, y = nbFunction(23, 34)

print(z)
print(y)

Output:

23
34

Summary

The above methods deal with the problem “TypeError: cannot unpack non-iterable NoneType object”. If you have any questions or helpful solutions, feel free to leave them in the comment below, and don’t forget to wait for our new articles in LearnShareIt.

Maybe you are interested:

Leave a Reply

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