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
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, 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!
Table of Contents
Hide
- What is Unpacking in Python?
- What is TypeError: cannot unpack non-iterable NoneType object
- How to resolve TypeError: cannot unpack non-iterable NoneType object
- Scenario 1: Unpacking iterables with built-in methods
- Scenario 2: Unpacking user-defined function which returns multiple values
- 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
.
The Python error message cannot unpack non-iterable NoneType object
typically occurs when we try to unpack a None
value as if it were an iterable object. In this guide, we’ll explore what this error means, why it occurs, and how to fix it.
Let’s take a closer look at the error message:
TypeError: cannot unpack non-iterable NoneType object
The first part of the message tells us that we’ve encountered a TypeError
, which is an error that occurs when we try to perform an operation on a value of the wrong type. The second part of the message tells us that we’re trying to unpack a non-iterable
NoneType
object.
In Python, an iterable is an object that can be looped over, such as a list
, tuple
, or dictionary
. And unpacking refers to extracting values from an iterable object and assigning them to individual variables.
Example: Unpacking in Python
In this example, we have defined a tuple my_tuple
that contains three values. We then unpack the tuple into variables a
,b
, and c
using the assignment statement. Each value in the tuple is assigned to a separate variable, which we can then use in our program.
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
The NoneType
object is a special type in Python that represents the absence of a value. It is used to indicate that a variable or expression does not have a value or has an undefined value. The None
object is the sole instance of the NoneType
class, and it is commonly used as a placeholder or default value in Python programs.
So, when we try to unpack a NoneType
object as if it were an iterable, Python raises a TypeError
.
Common Causes of TypeErrors
There are a few reasons why this error might occur. Some common causes include:
- A variable is not assigned a value, or it is assigned a
None
value. - The variable is assigned to an object that is not iterable.
- A function is returning a
None
value instead of an iterable object.
Here’s an example:
my_list = None
a, b, c = my_list
In this case, we’ve assigned the value None
to the variable my_list
. When we try to unpack my_list
into a
, b
, and c
, Python raises a TypeError
, because None
is not an iterable object.
This results in the following output when we execute the above program:
Traceback (most recent call last):
File "c: UsersnameOneDriveDesktopdemo.py", line 2, in <module>
a, b, c = my_list
^^^^^^^
TypeError: cannot unpack non-iterable NoneType object
How to Fix the TypeError
To fix the TypeError: cannot unpack non-iterable NoneType object
error, we need to ensure that the variable we are trying to unpack is an iterable object. Here are some ways to resolve the issue:
- Check that the variable we’re trying to unpack has a value, and is not
None
. If the variable isNone
, assign a valid value to it before trying to unpack it. - Make sure that the variable is actually an iterable object, such as a
list
or atuple
. If the variable is not iterable, we may need to reassign it to a different value or modify it to make it iterable. - Wrap the unpacking statement in a
try-except
block, so we can handle theTypeError
if it occurs. This can be useful if we’re not sure whether the variable we’re trying to unpack will be iterable or not.
Example Fix
In this example, we have wrapped the unpacking statement in a try-except
block. If my_list
is None, the try block will raise a TypeError
, and the except
block will print an error message instead of crashing the program and the remaining code will continue executing.
my_list = None
try:
a, b, c = my_list
except TypeError:
print("Cannot unpack non-iterable NoneType object")
print("My remaining code part")
Output:
Cannot unpack non-iterable NoneType object
My remaining code part
To conclude, the TypeError: cannot unpack non-iterable NoneType object
is a typical Python error that happens when we attempt to unpack a non-iterable object with a None
value. This problem may be avoided by first determining whether the variable is None
before attempting to unpack it. To handle None
values and avoid the application from crashing, conditional statements or try-except
blocks can be utilized.
As this issue can occur in a variety of circumstances, such as function returns, variable assignments, and list comprehensions, it’s critical to understand what’s causing it and how to handle it correctly. By being aware of this mistake and taking necessary procedures to handle None
values, we can develop more robust and error-free Python applications.
Track, Analyze and Manage Errors With Rollbar
Python provides a rich set of tools for developing and debugging code, but errors can still occur during development or execution. Being able to track, analyze, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!