How to Iterate Over a Float Object in Python

In Python, a float is a variable that is designed to store numeric values with decimal parts. Usually, you cannot iterate over a float object directly, as the concept of iteration generally applies to sequence types like lists, tuples or strings.

However, there are indirect ways to iterate over a float, such as converting the float to another iterable data type or using rounded float range values. Let’s see how you can achieve this in Python

Step 1: Python Basic Iteration Concept

When we talk about iteration, it generally applies to sequence types like lists, tuples or strings. Let’s illustrate this with an example:

In the above Python code, we iterated over the list sequence and printed each item. However, if we replace sequence with a float number:

Executing the above code will raise a TypeError, stating ‘float’ object is not iterable. This means, in Python, we cannot iterate over a float directly.

Step 2: Convert Float to String for Iteration

One way around this problem is to convert the float into a string, then iterate through each character. We can modify our previous example to demonstrate this:

1
2
3
4
5
2
.
5

Now, the script will iterate over each character in the float value, including the decimal point.

Step 3: Iterating Over Ranges of Float

Another approach is to create a function that behaves similar to the built-in range function but accepts float values. The function’s start and stop parameters can be float, and the function will yield a sequence of floating-point numbers.

This frange function returns a sequence of floating-point numbers from start (inclusive) to stop (exclusive) by step. The for loop utilizes this function to iterate over the sequence of float numbers.

0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0

The full provided code below:

Conclusion

Python’s flexibility allows us to solve problems from multiple angles. In the case of iterating over a float, although it cannot be done directly, we can use indirect methods like converting the float to a string or using a custom-made float range function.

Both methods have different use-cases and will be beneficial depending on your individual programming scenario.