Home >Backend Development >Python Tutorial >How to Generate Float Ranges in Python?
Float Equivalents for range() in Python
The Python range() function operates on integers, but is there a comparable function for floats? By default, range() produces a range of integers, even if the start and stop parameters are floats.
Consider the following example:
<code class="python">>>> range(0.5, 5, 1.5) [0, 1, 2, 3, 4]</code>
The output excludes the starting float (0.5) because the step size is an integer (1.5).
To retrieve a range of floats, you can employ one of the following approaches:
1. List Comprehension:
<code class="python">[x / 10.0 for x in range(5, 50, 15)]</code>
This method creates a list of floats by dividing each integer in the range by 10.0.
2. Lambda Function and map():
<code class="python">map(lambda x: x / 10.0, range(5, 50, 15))</code>
This method combines a lambda function with the map() function. The lambda function converts each integer in the range to a float by dividing it by 10.0.
The above is the detailed content of How to Generate Float Ranges in Python?. For more information, please follow other related articles on the PHP Chinese website!