TypeError: cannot unpack non-iterable float object (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: cannot unpack non-iterable float object (Python) #

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

typeerror cannot unpack non iterable float object

Here is an example of how the error occurs.

main.py
my_float = 3.1 # ⛔️ TypeError: cannot unpack non-iterable float object a, b = my_float

We are trying to unpack a floating-point number, but floats are not iterable.

You can use a tuple or a list of floats.

main.py
my_tuple = (3.1, 6.2) a, b = my_tuple print(a) # 👉️ 3.1 print(b) # 👉️ 6.2

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 a tuple or a list of floats from the function.

main.py
def get_list(): return [3.1, 6.2] a, b = get_list() print(a) # 👉️ 3.1 print(b) # 👉️ 6.2

The get_list function returns a list 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
example = 3.1 if not isinstance(example, float): a, b = example else: # 👇️ this runs print('Variable stores a float')

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

main.py
example = 3.1 if isinstance(example, float): example = (0, 0) a, b = example print(a, b) # 👉️ 0, 0

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

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

main.py
my_float = 3.14 print(type(my_float)) # 👉️ <class 'float'> print(isinstance(my_float, float)) # 👉️ True my_list = [3.1, 6.2] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ 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.