Cannot unpack non iterable nonetype object ошибка

When you're working with iterable objects like Lists, Sets, and Tuples in Python, you might want to assign the items in these objects to individual variables. This is a process known as unpacking. During the process of unpacking items in iterable objects, you may get an error that says: "TypeError: cannot unpack non-iterable NoneType object". This error mainly happens when you try to assign an object with a None type to a set of individual variables. This may sound confusing at the moment, bu

Typeerror: cannot unpack non-iterable nonetype object – How to Fix in Python

When you’re working with iterable objects like Lists, Sets, and Tuples in Python, you might want to assign the items in these objects to individual variables. This is a process known as unpacking.

During the process of unpacking items in iterable objects, you may get an error that says: «TypeError: cannot unpack non-iterable NoneType object».

This error mainly happens when you try to assign an object with a None type to a set of individual variables. This may sound confusing at the moment, but it’ll be much clearer once we see some examples.

Before that, let’s talk about some of the key terms seen in the error message. We’ll discuss the following terms: TypeError, unpacking, and NoneType.

What Is a TypeError in Python?

A TypeError in Python occurs when incompatible data types are used in an operation.

An example of a TypeError, as you’ll see in the examples in the sections that follow, is the use of a None data type and an iterable object in an operation.

What Is Unpacking in Python?

To explain unpacking, you have to understand what packing means.

When you create a list with items in Python, you’ve «packed» those items into a single data structure. Here’s an example:

names = ["John", "Jane", "Doe"]

In the code above, we packed «John», «Jane», and «Doe» into a list called names.

To unpack these items, we have to assign each item to an individual variable. Here’s how:

names = ["John", "Jane", "Doe"]

a, b, c = names

print(a,b,c)
# John Jane Doe

Since we’ve created the names list, we can easily unpack the list by creating new variables and assigning them to the list: a, b, c = names.

So a will take the first item in the list, b will take the second, and c will take the third. That is:

a = «John»
b =  «Jane»
c = «Doe»

What Is NoneType in Python?

NoneType in Python is a data type that simply shows that an object has no value/has a value of None.

You can assign the value of None to a variable but there are also methods that return None.

We’ll be dealing with the sort() method in Python because it is most commonly associated with the «TypeError: cannot unpack non-iterable NoneType object» error. This is because the method returns a value of None.

Next, we’ll see an example that raises the «TypeError: cannot unpack non-iterable NoneType object» error.

In this section, you’ll understand why we get an error for using the sort() method incorrectly before unpacking a list.

names = ["John", "Jane", "Doe"]

names = names.sort()

a, b, c = names

print(a,b,c)
# TypeError: cannot unpack non-iterable NoneType object

In the example above, we tried to sort the names list in ascending order using the sort() method.

After that, we went on to unpack the list. But when we printed out the new variables, we got an error.

This brings us to the last important term in the error message: non-iterable. After sorting, the names list became a None object and not a list (an iterable object).

This error was raised because we assigned names.sort() to names. Since names.sort() returns None, we have overridden and assigned None to a variable that used to be a list. That is:

names = names.sort()
but names.sort() = None
so names = None

So the error message is trying to tell you that there is nothing inside a None object to unpack.

This is pretty easy to fix. We’ll do that in the next section.

How to Fix “TypeError: Cannot Unpack Non-iterable NoneType Object” Error in Python

This error was raised because we tried to unpack a None object. The simplest way around this is to not assign names.sort() as the new value of your list.

In Python, you can use the sort() method on a collection of variables without the need to reassign the result from the operation to the collection being sorted.

Here’s a fix for the problem:

names = ["John", "Jane", "Doe"]

names.sort()

a, b, c = names

print(a,b,c)
Doe Jane John

Everything works perfectly now. The list has been sorted and unpacked.

All we changed was names.sort() instead of using names = names.sort().

Now, when the list is unpacked, a, b, c will be assigned the items in names in ascending order. That is:

a = «Doe»
b = «Jane»
c = «John»

Summary

In this article, we talked about the «TypeError: cannot unpack non-iterable NoneType object» error in Python.

We explained the key terms seen in the error message: TypeError, unpacking, NoneType, and non-iterable.

We then saw some examples. The first example showed how the error could be raised by using the sort() incorrectly while the second example showed how to fix the error.

Although fixing the «TypeError: cannot unpack non-iterable NoneType object» error was easy, understanding the important terms in the error message is important. This not only helps solve this particular error, but also helps you understand and solve errors with similar terms in them.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Table of Contents
Hide
  1. What is Unpacking in Python?
  2. What is TypeError: cannot unpack non-iterable NoneType object
  3. How to resolve TypeError: cannot unpack non-iterable NoneType object
    1. Scenario 1: Unpacking iterables with built-in methods
    2. Scenario 2: Unpacking user-defined function which returns multiple values
  4. Conclusion

The TypeError: cannot unpack non-iterable NoneType object occurs when we try to unpack the values from the method that does not return any value or if we try to assign the None value while unpacking the iterables.

In this tutorial, we will look into what exactly is TypeError: cannot unpack non-iterable NoneType object and how to resolve the error with examples.

What is Unpacking in Python?

In Python, the function can return multiple values, and it can be stored in the variable. This is one of the unique features of Python when compared to other languages such as C++, Go Java, C#, etc. 

Unpacking in Python is an operation where an iterable of values will be assigned to a tuple or list of variables.

Example of List Unpacking

x,y,z = [5,10,15]
print(x)
print(y)
print(z)

Output

5
10
15

First, let us see how to reproduce this issue and why developers face this particular issue with a simple example.

# list of cars
my_cars = ["Ford", "Audi", "BMW"]

# sort the cars in Alphabetical Order
my_cars = my_cars.sort()

# unpack cars into different variables
a, b, c = my_cars

print("Car", a)
print("Car", b)
print("Car", c)

Output

Traceback (most recent call last):
  File "c:PersonalIJSCodecode22.py", line 8, in <module>
    a, b, c = my_cars
TypeError: cannot unpack non-iterable NoneType object

In the above example, we have a simple list, and we are sorting the list in alphabetical order and then unpacking them into different variables.

The sort() function sorts the elements in alphabetical order by modifying the same object and does not return any value. The return type will be considered as None value.

The sort() method returns None value and here we are assigning the None value to the my_cars variable.

We are unpacking the None value into each of these variables, which results in  TypeError: cannot unpack non-iterable NoneType object

The same can happen when we use the user-defined function, which returns the None Value or if you have forgotten the return statement inside your function. In simple terms, any method that does not return a value or if it returns the value of None will lead to this error.

How to resolve TypeError: cannot unpack non-iterable NoneType object

We can resolve the cannot unpack non-iterable NoneType object by ensuring the unpacked items does not contain None values while assigning to the variables.

Let us see the various scenarios and the solutions for each scenario.

Scenario 1: Unpacking iterables with built-in methods

In the case of unpacking iterables we need to ensure that we are not using any built-in methods that return None while assigning it to variables.

In our above example, we have used the sort() method, which returns None value, and because of it, we get the TypeErrror.

As shown below, we can resolve the issue by first sorting the list and then unpacking the items. We have not assigned the None value to any variable here. The sort() doesn’t return any value however it modifies the original list into alphabetical order here. Hence unpacking the list works as expected in this case.

# list of cars
my_cars = ["Ford", "Audi", "BMW"]

# sort the cars in Alphabetical Order
my_cars.sort()

# unpack cars into different variables
a, b, c = my_cars

print("Car", a)
print("Car", b)
print("Car", c)

Output

Car Audi
Car BMW
Car Ford

.

Scenario 2: Unpacking user-defined function which returns multiple values

If you have written a custom function that returns multiple values, you need to ensure that the return value should not be of None value while unpacking the items.

Also, we need to ensure that the function has a proper return statement defined; else, it could also lead to the TypeError: cannot unpack non-iterable NoneType object.

def custom_function(a, b):
    return a

x, y = custom_function(5, 10)
print(x)
print(y)

Output

Traceback (most recent call last):
  File "c:PersonalIJSCodecode22.py", line 5, in <module>
    x, y = custom_function(5, 10)
TypeError: cannot unpack non-iterable int object

Solution

Here we need to return both a and b with proper values as we are unpacking 2 items. If any of it is None or if we do not return 2 values then you will get an TypeError exception again.

def custom_function(a, b):
    return a,b

x, y = custom_function(5, 10)
print(x)
print(y)

Output

5
10

Conclusion

The TypeError: cannot unpack non-iterable NoneType object occurs when we try to unpack the values from the method that returns multiple values as None value or if we try to assign the None value while unpacking the iterables.

We can resolve the issue by ensuring the function has a proper return statement. 

Also, when we try to unpack the values from a method and assign the values to the variables, we need to make sure the values are not of type None.

In Python, you can unpack iterable objects and assign their elements to multiple variables in the order that they appear. If you try to unpack a NoneType object, you will throw the error TypeError: cannot unpack non-iterable NoneType object. A NoneType object is not a sequence and cannot be looped or iterated over.

To solve this error, ensure you do not assign a None value to the variable you want to unpack. This error can happen when calling a function that does not return a value or using a method like sort(), which performs in place.

This tutorial will go through the error in detail and an example to learn how to solve it.


Table of contents

  • TypeError: cannot unpack non-iterable NoneType object
    • What is a TypeError?
    • What is Unpacking in Python?
  • Example
    • Solution
  • Summary

TypeError: cannot unpack non-iterable NoneType object

What is a TypeError?

TypeError occurs in Python when you perform an illegal operation for a specific data type. NoneType is the type for an object that indicates no value. None is the return value of functions that do not return anything. Unpacking is only suitable for iterable objects,

What is Unpacking in Python?

Unpacking is the process of splitting packed values into individual elements. The packed values can be a string, list, tuple, set or dictionary. During unpacking, the elements on the right-hand side of the statement are split into the values on the left-hand side based on their relative positions. Let’s look at the unpacking syntax with an example:

values = [40, 80, 90]

x, y, z = values

print(f'x: {x}, y: {y}, z: {z}')

The above code assigns the integer values in the value list to three separate variables. The value of x is 40, y is 80, and the value of z is 90. Let’s run the code to get the result:

x: 40, y: 80, z: 90

You can also unpack sets and dictionaries. Dictionaries are only ordered for Python version 3.7 and above but are unordered for 3.6 and below. Generally, it is not recommended to unpack unordered collections of elements as there is no guarantee of the order of the unpacked elements.

You cannot unpack a None value because it is not an iterable object, and an iterable is a Python object that we can use as a sequence. You may encounter this error by unpacking the result from a function that does not have a return statement.

Example

Let’s look at an example of a list of weights in kilograms that we want to sort and then unpack and print to the console.

# List of weights

weights = [100, 40, 50]

# Sort the list

weights = weights.sort()

# Unpack

a, b, c = weights

# Print Values to Console

print('Light: ', a)

print('Medium: ', b)

print('Heavy: ', c)

Let’s run the code to see the result:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      9 # Unpack
     10 
---≻ 11 a, b, c = weights
     12 
     13 # Print Values to Console

TypeError: cannot unpack non-iterable NoneType object

The program throws the error because the sort() method sorts the list of weights in place and returns None. However, we assigned the result of sort() to the variable weights, so when we try to unpack weights, we attempt to unpack a None value, which is not possible.

Solution

To solve the error, we need to ensure we are not assigning a None value to the list variable weights. Let’s look at the revised code:

# List of weights

weights = [100, 40, 50]

# Sort the list

weights.sort()

# Unpack

a, b, c = weights

# Print Values to Console

print('Light: ', a)

print('Medium: ', b)

print('Heavy: ', c)

Instead of assigning the sort() function result to the weights variable, we sort the list in place. Let’s run the code to see what happens:

Light:  40
Medium:  50
Heavu:  100

The program successfully sorts the list of weights and unpacks them into three variables, and prints the values to the console.

Summary

Congratulations on reading to the end of this tutorial. The NoneType object is not iterable, and when you try to unpack it, we will throw the error: “TypeError: cannot unpack non-iterable NoneType object”. A common cause of this error is when you try to unpack values from a function that does not return a value. To solve this error, ensure that the value you attempt to unpack is a sequence, such as a list or a tuple.

For more reading on what you can do with iterable objects go to the article called: How to Use the Python Map Function.

For more reading on cannot unpack non-iterable object errors, go to the articles:

  • How to Solve Python TypeError: cannot unpack non-iterable int object
  • How to Solve Python TypeError: cannot unpack non-iterable float object

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Python sequences can be unpacked. This means you can assign the contents of a sequence to multiple variables. If you try to unpack a None value using this syntax, you’ll encounter the “TypeError: cannot unpack non-iterable NoneType object” error.

In this guide, we break down what this error means and why you may see it. We discuss an example of this error in action so you can figure out how to solve it.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

TypeError: cannot unpack non-iterable NoneType object

Unpacking syntax lets you assign multiple variables at the same time based on the contents of a sequence. Consider the following code:

fruit_sales = [230, 310, 219]
avocado, bananas, apples = fruit_sales

This code lets us assign the values in the fruit_sales variable to three separate variables. The value of “avocado” becomes 230, the value of “bananas” becomes 310, and the value of “apples” becomes 219.

The unpacking syntax only works on sequences, like lists and tuples. You cannot unpack a None value because None values are not sequences.

This error is commonly raised if you try to unpack the result of a function that does not include a return statement.

An Example Scenario

We’re going to create a program that calculates the average purchase price at a coffee shop and the largest purchase made on a given day.

Start by defining a list of purchases made on a particular day:

purchases = [2.30, 3.90, 4.60, 7.80, 2.20, 2.40, 8.30]

Next, define a function. This function will calculate the average purchase price and the largest purchase made on a given day:

def calculate_statistics(purchases):
	    average_purchase = sum(purchases) / len(purchases)
	    largest_purchase = max(purchases)

To calculate the average value of a purchase, divide the total value of all purchases by how many purchases are made on a given day. We use the max() function to find the largest purchase.

Now that we’ve defined our function, we can call it. We assign the values our function returns to variables:

average, largest = calculate_statistics(purchases)

We use the unpacking syntax to access these two values from our function.

This code lets us access the values our function returns in our main program. Now that we have access to these values outside our function, we print them to the console:

print("The average purchase was ${}.".format(round(average, 2)))
print("The largest purchase was ${}.".format(round(largest, 2)))

Our code will show us the average purchase value and the value of the largest purchase on the console. We round both of these values to two decimal places using the round() method. Let’s run our program and see what happens:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
	average, largest = calculate_statistics(purchases)
TypeError: cannot unpack non-iterable NoneType object

Our code returns an error message.

The Solution

The error occurs on the line where we try to unpack the values from our function.

Our error message tells us we’re trying to unpack values from a None value. This tells us our function is not returning the correct values.

If we take a look at our function, we see we’ve forgotten a return statement. This means our code cannot unpack any values.

To solve this error, we must return the “average_purchase” and “largest_purchase” values in our function so we can unpack them in our main program:

def calculate_statistics(purchases):
	    average_purchase = sum(purchases) / len(purchases)
	    largest_purchase = max(purchases)

	    return average_purchase, largest_purchase

Let’s run our code:

The average purchase was $4.5.
The largest purchase was $8.3.

Our code tells us the average purchase was $4.50 and the largest purchase was $8.30.

Conclusion

The “TypeError: cannot unpack non-iterable NoneType object” error is raised when you try to unpack values from one that is equal to None.

A common cause of this error is when you try to unpack values from a function that does not return a value. To solve this error, make sure the value you are trying to unpack is a sequence, such as a list or a tuple.

You’re now ready to solve this error like a professional!

I know this question has been asked before but I can’t seem to get mine to work.

import numpy as np


def load_dataset():
    def download(filename, source="http://yaan.lecun.com/exdb/mnist/"):
        print ("Downloading ",filename)
        import urllib
        urllib.urlretrieve(source+filename,filename)

    import gzip
    
    def load_mnist_images(filename):
        if not os.path.exists(filename):
            download(filename)
        with gzip.open(filename,"rb") as f:
            data=np.frombuffer(f.read(), np.uint8, offset=16)
            
            data = data.reshape(-1,1,28,28)
            
            return data/np.float32(256)

        def load_mnist_labels(filename):
            if not os.path.exists(filename):
                download(filename)
            with gzip.open(filename,"rb") as f:
                data = np.frombuffer(f.read(), np.uint8, offset=8)
            return data

        X_train = load_mnist_images("train-images-idx3-ubyte.gz")
        y_train = load_mnist_labels("train-labels-idx1-ubyte.gz")
        X_test = load_mnist_images("t10k-images-idx3-ubyte.gz")
        y_test = load_mnist_labels("t10k-labels-idx1-ubyte.gz")

        return X_train, y_train, X_test, y_test


X_train, y_train, X_test, y_test = load_dataset()


import matplotlib
matplotlib.use("TkAgg")

import matplotlib.pyplot as plt
plt.show(plt.imshow(X_train[3][0]))

This is the error I am getting:

Traceback (most recent call last):
  File "C:UsersnehadDesktopNehaNon-SchoolPythonHandwritten Digits 
Recognition.py", line 38, in <module>
    X_train, y_train, X_test, y_test = load_dataset()
TypeError: cannot unpack non-iterable NoneType object

I am new to machine learning. Did I just miss something simple? I am trying a Handwritten Digit Recognition project for my school Science Exhibition.

In Python, we can unpack iterable objects and assign their element value to multiple variables. But if we try to unpack a NoneType object value

None

, we will encounter the «TypeError: cannot unpack non-iterable NoneType object» Error.

In this Python guide, we will discuss this error in detail and learn how to fix it. We will also walk through an example scenario, so you can figure out how to solve this error for yourself.

Python Problem: Python Program to Swap Two Variables

In Python unpacking, we can assign iterable object’s (string, tuple, list, set, and dictionary) items to the multiple variables using a single-line statement.

For example

# list object
my_list= [20, 30, 40]

# unpacking
x, y, z = my_list

The above code will unpack the list

my_list

and assign the values 20 to x, 30 to y, and 40 to z.

The unpacking can only be performed using an iterable object. And if we try to perform it on a None value, we will receive the error

TypeError: cannot unpack non-iterable NoneType object

. The Error statement «TypeError: cannot unpack non-iterable NoneType object» has two parts.

  1. TypeError.
  2. cannot unpack non-iterable NoneType object

1. TypeError

TypeError is a Python standard exception. This exception is raised in a Python program when performing an invalid or unsupported operation on a Python object. When we perform unpacking on a None value, we receive a TypeError exception.

2. cannot unpack non-iterable NoneType object

This is the error message that tags along with the Python TypeError exception. The error message is clearly telling us that we are trying to unpack a non-iterable

NoneType object

, which is not supported in Python. You will only encounter this error in your Python program when you try to unpack a None value.


Example

# None unpacking
a, b, c = None


Output

Traceback (most recent call last):
  File "main.py", line 2, in 
    a, b, c = None
TypeError: cannot unpack non-iterable NoneType object

Common Example Scenario

Encountering this error is common when you are trying to unpack an iterable object, and for some reason, you declare that iterable object as a None value.


Example

Let’s say you have a list

prices

that contains three price ranges for a similar product. And need to

write a program

that sorts the

prices

list and assigns the three prices to the

expensive

,

medium

and

cheap

variables.

# list
prices = [100, 50, 200]

# sort the list
prices = prices.sort()

# unpack
cheap, medium, expensive = prices
print("Expensive: ", expensive)
print("Medium: ", medium)
print("Cheap: ", cheap)


Output

Traceback (most recent call last):
  File "main.py", line 8, in 
    expensive, medium, cheap = prices
TypeError: cannot unpack non-iterable NoneType object


Break the code

In the above example, we are receiving an error in line 8 with

expensive, medium, cheap = prices

. This is because at that statement, the value of prices in

None

.

In line 5, we are sorting the list with statement

prices = prices.sort()

. The list sort() method sorts the list in place and returns None. At that point, the value of

prices

became

None

and when we tried to unpack it, we received the «TypeError: cannot unpack non-iterable NoneType object» Error.

Solution

To solve the above problem, we need to make sure that we are not assigning any None value to the list

prices

.

# list
prices = [100, 50, 200]

# sort the list
prices.sort()

# unpack
cheap, medium, expensive = prices

print("Expensive: ", expensive)
print("Medium: ", medium)
print("Cheap: ", cheap)


Output

Expensive: 200
Medium: 100
Cheap: 50

Wrapping Up!

In this Python tutorial, we learned why «TypeError: cannot unpack non-iterable NoneType object» is raised in a Python program. The NoneType object value None

is not iterable

, and when we try to unpack it, we encounter this error. To fix this error, you need to make sure that you are not unpacking the None value in your program. A common case when you encounter this error is when you unpack a return value from a method or function that returns None.

So be careful with the value you are receiving. If you are still getting this error in your Python program, you can share your code and query in the comment section. We will try to help you in debugging.


People are also reading:

  • Python TypeError: object of type ‘int’ has no len() Solution

  • Gmail API in Python

  • Python AttributeError: A Complete Guide

  • Delete Emails in Python

  • Python TypeError: Method_Name() missing 1 required positional argument: ‘self’ Solution

  • Numpy dot Product

  • Python TypeError: can only join an iterable Solution

  • String count() in Python

  • Python KeyError: A Complete Guide

  • np.arange() | NumPy Arange Function in Python

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.

  • BaseException
    • Exception
      • TypeError

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

“Learn From Others Experience»

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Cannot sign data error description zakupki gov ru
  • Cannot show requested dialog sqlmgmt как исправить
  • Cannot send session cache limiter headers already sent как исправить
  • Cannot run preview graph amcap как исправить
  • Cannot retrieve speedtest configuration error http error 403 forbidden

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии