[Solved]: Python TypeError: cannot unpack non-iterable NoneType object

In Python, TypeError is subclass of Exception. Python sequence can be unpacked. This means you can assign content of sequence to multiple variables. If you try to assign a None value to a variable by using this syntax then it throws error as “TypeError: Can not unpack Non-iterable None Type object”.

Note: Syntax error should not be handle through exception handling it should be fixed in your code.

You can check complete list of built-in exception hierarchy by following link. Python: Built-in Exceptions Hierarchy

How to unpack sequence elements to variables?

In this below unpacking sequence the elements of list will assign to variables in sequence. For example:

fruit_prices = [250, 80, 200]
grapes, bananas, apples = fruit_price

In the above code the values in fruit_prices will assign in variables as below :

grapes=250, bananas=80, apples=200

Lets take another example of unpacking sequence from function where return values from functions can be assigned in sequence of variables. For Example:

prices = [4.30, 5.90, 6.70, 3.90, 5.60, 8.30, 6.50]
def calculate_statistics(prices):
    average_price = sum(prices) / len(prices)
    largest_price = max(prices)
    return average_price, largest_price
average, largest = calculate_statistics(prices)
print("Average :"+str(average))
print("Largest :"+str(largest))

In this above example, If you will see it’s returning two values (line 5) from calculate_statistics function and returned values will assign to variables average and largest in sequence (line 6).

Average : 5.88

Largest : 8.30

Scenario for Exception

Now lets create scenario for creating exception, I have modified the above code with comments the line # 5. It will display the code as below

prices = [4.30, 5.90, 6.70, 3.90, 5.60, 8.30, 6.50]
def calculate_statistics(prices):
    average_price = sum(prices) / len(prices)
    largest_price = max(prices)
    #return average_price, largest_price
average, largest = calculate_statistics(prices)
print("Average :"+str(average))
print("Largest :"+str(largest))

When you execute the above code will through exception as below

average, largest = calculate_statistics(prices)

TypeError: ‘NoneType’ object is not iterable

In this example, Hope you understand the scenario as the number of values in sequence will assigned to value on same number of value.

Learn Python exception handling in more detain in topic Python: Exception Handling

2 thoughts on “[Solved]: Python TypeError: cannot unpack non-iterable NoneType object”