TypeError: cannot unpack non-iterable numpy.float64 object

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

TypeError: cannot unpack non-iterable numpy.float64 object #

The Python "TypeError: cannot unpack non-iterable numpy.float64 object" occurs when we try to unpack a numpy float value. To solve the error, track down where the variable got assigned a numpy float and correct the assignment to an iterable, e.g. an array, a list or a tuple.

typeerror cannot unpack non iterable numpy float64 object

Here is an example of how the error occurs.

main.py
import numpy as np my_float = np.float64(3.14) # ⛔️ TypeError: cannot unpack non-iterable numpy.float64 object a, b = my_float

We are trying to unpack a numpy float, but floats are not iterable.

You can use an array, a tuple or a list of floats.

main.py
import numpy as np arr = np.array([3.14, 6.28], dtype=np.float64) a, b = arr print(a) # 👉️ 3.14 print(b) # 👉️ 6.28

The variables need to be exactly as many as the values in the iterable.

You can use this approach if you need to initialize multiple variables to 0.

main.py
a, b, c = 0, 0, 0 print(a, b, c) # 👉️ 0, 0, 0

If you are unpacking the result of calling a function, make sure to return an iterable containing floating-point numbers from the function.

main.py
import numpy as np def get_arr(): return np.array([3.14, 6.28], dtype=np.float64) a, b = get_arr() print(a) # 👉️ 3.14 print(b) # 👉️ 6.28

The get_arr function returns an array of floats, so we can unpack the floats into variables.

Use an if statement if you need to check whether a variable doesn't store a float before unpacking.

main.py
import numpy as np example = np.float64(3.14) if not isinstance(example, float): a, b = example print(a, b) else: # 👇️ this runs print('variable stores a float value')

Alternatively, you can reassign the variable to an iterable if it stores a floating-point number.

main.py
import numpy as np example = np.float64(3.14) if isinstance(example, float): example = np.array([3.14, 6.28], dtype=np.float64) a, b = example print(a) # 👉️ 3.14 print(b) # 👉️ 6.28

We check if the example variable stores a float and if it does, we reassign it to an array.

If you aren't sure what type of object a variable stores, use the type() class.

main.py
import numpy as np my_float = np.float64(3.14) print(type(my_float)) # 👉️ <class 'numpy.float64'> print(isinstance(my_float, np.float64)) # 👉️ True my_arr = np.array([3.14, 6.28], dtype=np.float64) print(type(my_arr)) # 👉️ <class 'numpy.ndarray'> print(isinstance(my_arr, np.ndarray)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.