Often when working on a data analytics project it requires you to split data out into its constituent parts.
There are a number of reasons for this, it can be confusing when you get errors as with the title of this post.
Before we explain this error and what it means, lets us first explain unpacking
Unpacking basically means splitting something up into a number of its parts that make it up.
To demonstrate if you take a,b,c = 123, and look to unpack it, it throws out the error, but why?
Well pure and simple, we have three values on the left “a,b,c”, looking for three values on the right.
a,b,c = 123 print(a) Output: a,b,c = 123 TypeError: cannot unpack non-iterable int object
If you would like to fix this problem change the right hand side to have three values.
a,b,c = 1,2,3 print(a) print(b) print(c) print(a,b,c) Output: 1 2 3 1 2 3 Process finished with exit code 0
In essence, what is going on is that an evaluation checking that both sides have the same amount of values.
It is important to remember, the code above we used to show the error is an integer, which cannot be unpacked.
So if you take 123 for an example, which we used here it cannot be split into say 100 and 10 and 13.
In this case, even though when they are added up to 123, integers cannot be unpacked.
For this reason in the code for our solution, the difference is that the values used are tuples as follows:
a,b,c = 1,2,3 print(a) print(b) print(c) print(a,b,c) print(type((a,b,c))) Or a,b,c = (1,2,3) print(a) print(b) print(c) print(a,b,c) print(type((a,b,c))) yield the same result: 1 2 3 1 2 3 <class 'tuple'> Process finished with exit code 0
So in summary:
When unpacking there are a number of things to remember:
- Integers on their own cannot be unpacked.
- You need to make sure that if you have a number of variables, that you have the same number of integers if they the values.
- This will make it a tuple and unpacking can then happen.
Выражение for num, value in word, bb:
означает, что нужно перебрать коллекцию и каждый ее элемент распаковать по переменным num
и value
.
В цикле word, bb
станет кортежом на два элемента word
и bb
, т.е. сначала цикл вернет word
, потом bb
.
А значения num, value
заставят его каждый элемент пытаться разложить на два элемента. А т.к. у вас word
является числом, то для него такого нельзя сделать (cannot unpack non-iterable int object
).
Кст, распаковка выглядит так, для рабочего варианта сделал обе переменных строками по два элемента:
word, bb = '12', '34'
for num, value in word, bb:
print(num, '=>', value)
# 1 => 2
# 3 => 4
Как мы тут видим, сначала цикл вернул word
, после значение "12"
распаковал по двум переменным, а следующей итерацией вернул bb
и сделал аналогичную распаковку
Мб, вам не цикл нужен был, а что-то вроде такого?
num, value = word, bb
print(str(num) + '==>' + value)
In Python, you can unpack iterable objects and assign their elements to multiple variables in the order they appear. If you try to unpack an integer, you will throw the error TypeError: cannot unpack non-iterable int
object. An integer is not a sequence which we can loop over.
To solve this error, you can perform unpacking on a list or tuple of integers. For example,
int_x, int_y, int_z = (1, 2, 3) print(int_x) print(int_y) print(int_z)
This tutorial will go through how to solve the error with code examples.
Table of contents
- TypeError: cannot unpack non-iterable int object
- What is an Iterable Object in Python?
- What is Unpacking in Python?
- Example
- Solution
- Summary
TypeError: cannot unpack non-iterable int object
TypeError occurs in Python when you perform an illegal operation for a specific data type. Integers are zero, positive or negative whole numbers without a fractional component and are not iterable. Unpacking is only suitable for iterable objects.
What is an Iterable Object in Python?
An iterable is an object that can be “iterated over“, for example in a for loop. In terms of dunder methods under the hood, an object can be iterated over with “for
” if it implements __iter__()
or __getitem__()
.
An iterator returns the next
value in the iterable object. An iterable generates an iterator when it is passed to the iter()
method.
In terms of dunder methods under the hood, an iterator is an object that implements the __next__()
method.
A for loop automatically calls the iter()
method to get an iterator and then calls next
over and over until it reaches the end of the iterable object.
Unpacking requires an iteration in order to assign values to variables in order, and as such requires 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 = [10, 20, 30] 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 10
, y
is 20
, and the value of z
is 30
. Let’s run the code to get the result:
x: 10, y: 20, z: 30
We 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.
We cannot unpack an Integer because it is not an iterable object, and an iterable is a Python object that we can iterate over.
Example
Let’s look at an example of attempting to unpack an int object. First, we will define a function that returns an integer.
def return_int(): return 2
Next, we will try to unpack the object returned by the function and assign three values to the variables named x
, y
, and z
.
x, y, z = return_int() print(f'x: {x}, y: {y}, z: {z}')
Let’s run the code to see the result:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [18], in <cell line: 1>() ----> 1 x, y, z = return_int() 2 print(f'x: {x}, y: {y}, z: {z}') TypeError: cannot unpack non-iterable int object
The error occurs because the function returns an integer, and we are using an unpack operation, which is impossible with an integer because integers are not iterable.
We can use the type()
method to check the type of an object. Let’s verify the type of the object returned by the return_int()
function call:
print(type(return_int()))
<class 'int'>
Solution
We can solve this error by ensuring the function we use returns an iterable object. In this case, we will return a tuple containing three integers. Let’s look at the revised code:
def return_tuple(): return (2, 4, 8)
Next, we will call the return_tuple()
function to return the tuple
and unpack it.
x, y, z = return_tuple() print(f'x: {x}, y: {y}, z: {z}')
Let’s run the code to see the result:
x: 2, y: 4, z: 8
We successfully called the function and unpacked the tuple
into three variables, and printed their values to the console.
Summary
Congratulations on reading to the end of this tutorial!
For more reading on cannot unpack non-iterable object errors, go to the articles:
- How to Solve Python TypeError: cannot unpack non-iterable NoneType object
- How to Solve Python TypeError: cannot unpack non-iterable float object
- How to Solve Python TypeError: cannot unpack non-iterable numpy.float64 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!
In Python, only the sequences such as tuple, list, etc. can be unpacked. Unpacking means we can assign sequence elements to more than one variable. To unpack non-iterable int objects in a program, the Python interpreter throws a “TypeError”.
This write-up will provide a reason and the solution to the error “cannot unpack non-iterable int object” in Python. The given below factors are discussed in this Python blog post:
- Reason: Unpacking an Integer Value
- Solution 1: Use a Tuple or List of Integers
- Solution 2: Check Value Before Unpacking
So, let’s get started!
Reason: Unpacking an Integer Value
The main reason which causes the “cannot unpack non-iterable int object” error is when a user tries to unpack an integer value in a Python program. The unpacking is referred to as assigning multiple iterable values to a tuple or list variable using a single-line assignment statement.
The above snippet shows the “TypeError” because the integer object is not-iterable, and unpacking can not be performed on an integer.
Solution 1: Use a Tuple or List of Integers
To resolve this error, we need to correct the assignment and use “tuple” or “list” instead of non-iterable integers. Let’s understand it via the below code block:
Note: To assign individual digits of int value to a variable, we can convert the integer value to a string using the “str()” function.
Code:
num1, num2 = [55,66] print(num1) print(num2)
In the above code, the variables “num1” and “num2” are assigned a value “55” and “66” of the list element.
Output:
The above output successfully assigned the value to multiple variables in a single-line assignment statement.
Solution 2: Check Value Before Unpacking
To fix this error, we can also check the value before unpacking the variable, whether it is an integer or not. For instance, the below code block shows the solution:
Code:
num = 23 if not isinstance(num, int): x, y = num print(x) print(y) else: print('variable is integer')
In the above code, the “isinstance()” function is used to check whether the input variable “num” has an “integer” value or not. If the value is an integer, then the “if” block executes the program; otherwise, the else block is executed.
Output:
The above output uses an “if-else” statement to check the value before unpacking.
Conclusion
The “cannot unpack non-iterable int object” error occurs when users unpack the non-iterable integer value in a Python program. To resolve this “cannot unpack non-iterable int object” error, various solutions, such as using a tuple or list and checking the value before unpacking, are used in Python. The “if-else” statement is used along with the “isinstance()” function to check the integer value before unpacking. This article has presented a complete guide on rectifying Python’s “cannot unpack non-iterable int object” error.
One error that you might encounter when running Python code is:
TypeError: cannot unpack non-iterable int object
This error occurs when you mistakenly attempt to unpack a single int
object.
To fix this error, you need to use the unpacking assignment only on iterable objects, like a list or a tuple.
This tutorial will show you an example that causes this error and how to fix it.
How to reproduce this error
Here’s an example code that produces this error:
first, second = 2
# TypeError: cannot unpack non-iterable int object
At times, people encounter this error when they attempt to unpack the values returned by a function.
Suppose we have a function with an if-else
condition, and the conditions have different return values as follows:
def get_coordinates(x, y):
if y > 1:
return (x , y)
else:
return x
The if
condition returns a tuple, while the else
condition only returns a single value x
.
Next, we call the function as follows:
a, b = get_coordinates(27, 0)
Because the arguments fit the else
condition, the single value is returned, and the unpacking assignment causes this error:
Traceback (most recent call last):
File "main.py", line 7, in <module>
a, b = get_coordinates(27, 0)
TypeError: cannot unpack non-iterable int object
You need to put something in the return
statement of the else
condition that will be assigned to the b
variable.
How to fix this error
To resolve this error, you need to make sure that you have an iterable object passed to the unpacking assignment.
When you have two variables to assign, specify two values in the assignment like this:
When you pass two values as shown above, Python will convert the values into a tuple automatically.
The same solution applies when you have a function with if-else
conditions. Adjust the else
condition to return a tuple. If you have nothing to return, then just return 0
or None
value:
def get_coordinates(x, y):
if y > 1:
return (x , y)
else:
return (x, 0)
You can call the function again. This time, the same arguments work without causing the error.
Other variants of this error
This error has several variants as shown below:
- TypeError: cannot unpack non-iterable float object
- TypeError: cannot unpack non-iterable NoneType object
- TypeError: cannot unpack non-iterable bool object
- TypeError: cannot unpack non-iterable function object
- TypeError: cannot unpack non-iterable class object
These error messages are caused by the same problem: you are sending a non-iterable object to the unpacking assignment.
1. TypeError: cannot unpack non-iterable float object
This error occurs when you specify a single floating number to the unpacking assignment:
a, b = 3.44
# TypeError: cannot unpack non-iterable float object
To resolve this error, you need to send a tuple or a list of floats to the unpacking assignment. The following examples are valid:
a, b = 3.44, 0.0
a, b = 3.44, 0
a, b = [3.44, 0.0]
a, b = [3.44, 0]
2. TypeError: cannot unpack non-iterable NoneType object
This variant error occurs when you attempt to unpack a single None
value with the unpacking assignment.
Here’s an example that causes this error:
To resolve this error, modify the assignment and add another value to assign to the b
variable.
You can send any value you want:
3. TypeError: cannot unpack non-iterable bool object
This error occurs when you try to unpack a single bool
object using the unpacking assignment:
To resolve this error, make sure that you’re sending as many values as the variables used in the assignment:
This way, the error should be resolved.
4. TypeError: cannot unpack non-iterable function object
This error occurs when you assign a function to a variable using the unpacking assignment:
def get_rooms():
return 3, 5
a, b = get_rooms
If you want to call the function and assign the return values to the variables, then you’re missing the parentheses after the function name:
Without the parentheses, Python thinks you’re assigning the function object to another variable instead of calling the function.
Don’t forget to specify arguments for the function if you have any.
5. TypeError: cannot unpack non-iterable class object
This error occurs when you assign a class object to more than one variable using the unpacking assignment.
Suppose you have a Car
class defined as follows:
class Car:
def __init__(self, name):
self.name = name
Next, you attempt to create two Car
objects using the unpacking assignment:
my_car, my_second_car = Car('Toyota')
You receive this error:
my_car, my_second_car = Car('Toyota')
TypeError: cannot unpack non-iterable Car object
To resolve this error, you need to instantiate two objects for the two variables my_car
and my_second_car
.
my_car, my_second_car = Car('Toyota'), Car('Tesla')
Now that you have two Car
objects assigned to the two variables, the error is resolved.
Conclusion
The Python TypeError: cannot unpack non-iterable (type) object
occurs when you unpack an object that’s not iterable.
When you use the unpacking assignment, you need to specify an iterable object such as a list, a tuple, a dictionary, or a set in the assignment.
If you specify a single non-iterable object such as an integer, a boolean, a function, or a class, then this error will be raised.
I hope this tutorial is helpful. Happy coding! 👍