How to Solve TypeError: ‘float’ object is not iterable

by | Programming, Python, Tips

Floats and iterables are distinct objects In Python. A float is any decimal point number, and an iterable is an object capable of returning elements one at a time, for example, a list. A float is a single value and does not contain other values. If you try to iterate over a float, you will raise the error “TypeError: ‘float’ object is not iterable“.

To solve this error, ensure you use the range() method, for example,

for number in range(floating_point_number)

to iterate over a range of numbers up to the specified floating_point_number.

This tutorial will go through the error in detail. We will go through two example scenarios and learn how to solve them.


TypeError: ‘float’ object not iterable

What is a TypeError?

A TypeError occurs when we try to perform an operation on the wrong type of object. For example, if we try to calculate the square root of a list instead of an integer or a floating-point number, then a TypeError will be generated by the Python interpreter.

Difference Between a Float and an Iterable

Iterables are containers that can store multiple values and return them one by one. Iterables can store any number of values, and the values can either be the same type or different types. You can go to the next item in an iterable object using the next() method.

A floating-point number is any number with a decimal point. You can define a floating-point number in Python by defining a variable and assigning a decimal point number to it.

x = 4.2

print(type(x))
class 'float'

Floating-point numbers do not store multiple values like a list or a dictionary. If you try to iterate over a float, you will raise the error “TypeError: ‘float’ object is not iterable” because float does not support iteration.

You will get a similar error if you try to iterate over an integer or a NoneType object.

Example #1: Iterate Over a Floating Point Number

Let’s look at an example where we initialize a floating-point number and iterate over it.

# Define floating point number

float_num = 10.0 

# Iterate over the floating point number

for num in float_num:

    print(num)

Let’s see what happens when we run the code:

TypeError                                 Traceback (most recent call last)
      1 for num in float_num:
      2     print(num)
      3 

TypeError: 'float' object is not iterable

We raise the error because Python does not support iteration on a floating-point number.

Solution #1: Convert float to string Using the str() Method

The first solution involves converting the float_num object to a string using the str() method and iterating over every digit. We can do iteration over a string because the string type is iterable. However, the for loop will return each character of the float_num string.

# Define floating point number

float_num = 10.0 

# Iterate over the floating point number

for digit in str(float_num):

    print(digit)

Solution #2: Iterate Using the range() Method

To print the range of numbers, we can use the int() method to convert the number to an integer and then use the integer as input to the range() method. The range() method only accepts integer numbers, in which case we have to convert any floating-point number that we want to iterate over to an integer. The range() method returns an iterable object which we can iterate over using a for loop.

# Define floating point number

float_num = 30.0 

# Convert the float number to an integer

int_num = int(float_num)

# Iterate over the floating point number

for num in range(int_num):

    print(num)

Let’s see what happens when we run the revised code:

0
1
2
3
4
5
6
7
8
9

Example #2: Determine if a Number is Prime

Let’s look at another example where we write a program to check if a number entered by the user is prime or not. Prime numbers are only divisible by themselves, and 1. To start, we will ask the user to insert the number to determine whether it is prime or not.

number = float(input("Enter a number:  "))

Then we define a function that determines whether the number is prime by using the modulo operator %. If the remained of x % y equals zero, then y is a factor of x. Prime numbers have two factors, one and itself.

# Function to determine if number is prime or not

def prime_number_calc(num):

    for i in num:
        # Ensure we do not divide the number by zero or one

        if i > 1:

            if num % i == 0:

                 print(f'{num} is not prime')

                 break

    # If the loop runs completely the number is prime

    else:

        print(f'{num} is a prime number')
prime_number_calc(number)

Let’s run the code to see what happens:

TypeError                                 Traceback (most recent call last)
      1 def prime_number_calc(num):
      2     for i in num:
      3         if i > 1:
      4             if num % i == 0:
      5                 print(f'{num} is not prime')

TypeError: 'float' object is not iterable

The Python interpreter throws the TypeError because a floating-point number is not a suitable type to iterate over. A for loop requires an iterable object to loop over.

Solution

To solve this problem, we need to convert the input number to an integer using int() and pass the integer the range() method instead of the float. Let’s look at the revised code:

def prime_number_calc(num):

     for i in range(int(num)):

         if i > 1:

             if num % i == 0:

                 print(f'{num} is not prime')

                 break
     else:

         print(f'{num} is a prime number')
number = float(input("Enter a number:  "))

prime_number_calc(number)

Let’s run the code to see what happens:

Enter a number:  17.0

17.0 is a prime number

Our code successfully prints the result that 17.0 is a prime number.

Summary

Congratulations on reading to the end of this tutorial. The error “TypeError: ‘float’ object is not iterable” occurs when you try to iterate over a floating-point number as if it were an iterable object like a list.

You must use the range() method to iterate over a collection of numbers. However, you must convert the float to an integer beforehand passing it to the range() method. If you want to iterate over the digits of the float, you can convert the float to a string and use the range() function.

To learn more about Python for data science and machine learning, go to the online courses pages on Python for the best courses online!

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨