Calculating a range of an exact number of values in Python

list, python, range

Solution

Use linspace() from NumPy.

>>> from numpy import linspace
>>> linspace(-7.5, 0.1, 6)
array([-7.5 , -5.98, -4.46, -2.94, -1.42,  0.1])
>>> linspace(-7.5, 0.1, 6).tolist()
[-7.5, -5.9800000000000004, -4.46, -2.9399999999999995, -1.4199999999999999, 0.10000000000000001]

It should be the most efficient and accurate.

Problem

I'm building a range between two numbers (floats) and I'd like this range to be of an exact fixed length (no more, no less). `range` and `arange` work with steps, instead. To put things into pseudo Python, this is what I'd like to achieve: ``` start_value = -7.5 end_value = 0.1 my_range = my_range_function(star_value, end_value, length=6) print my_range [-7.50,-5.98,-4.46,-2.94,-1.42,0.10] ``` This is essentially equivalent to the R function `seq` which can specify a sequence of a given length. Is this possible in Python? Thanks.

Original source

Related problems