Home  >  Article  >  Backend Development  >  How to Generate Float Ranges in Python?

How to Generate Float Ranges in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-20 11:20:30530browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn