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.
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.
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:
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.
The above output uses an “if-else” statement to check the value before unpacking.
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.