Creating a range with fixed number of elements (length)

Question:

In Python, how can I create a list over a range with a fixed number of elements, rather than a fixed step between each element?

>>> # Creating a range with a fixed step between elements is easy:
>>> list(range(0, 10, 2))
[0, 2, 4, 6, 8]
>>> # I'm looking for something like this:
>>> foo(0, 10, num_of_elements=4)
[0.0, 2.5, 5.0, 7.5]
Asked By: LondonRob

||

Answers:

I use numpy for this.

>>> import numpy as np
>>> np.linspace(start=0, stop=7.5, num=4)
array([ 0. ,  2.5,  5. ,  7.5])
>>> list(_)
[0.0, 2.5, 5.0, 7.5]
Answered By: wim

You can easily produce such a list with a list comprehension:

def foo(start, stop, count):
    step = (stop - start) / float(count)
    return [start + i * step for i in xrange(count)]

This produces:

>>> foo(0, 10, 4)
[0.0, 2.5, 5.0, 7.5]
Answered By: Martijn Pieters

itertools.count can handle float:

>>> import itertools
>>> def my_range(start,stop,count):
...     step = (stop-start)/float(count)
...     for x in itertools.count(start,step):
...         if x < stop:
...             yield x
...         else:break
... 
>>> [x for x in my_range(0,10,4)]
[0, 2.5, 5.0, 7.5]
Answered By: Hackaholic

How about this:

>>> def foo(start=0, end=10, num_of_elements=4):
...     if (end-start)/num_of_elements != float(end-start)/num_of_elements:
...         end = float(end)
...     while start < end:
...         yield start
...         start += end/num_of_elements
...         
>>> list(foo(0, 10, 4))
[0, 2.5, 5.0, 7.5]
>>> list(foo(0, 10, 3))
[0, 3.3333333333333335, 6.666666666666667]
>>> list(foo(0, 20, 10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> 

It keeps your specification for the first element to be an integer and the others to be floats. But if you give it a step where the elements can stay as integers, they will.

Answered By: TessellatingHeckler
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.