Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a range with fixed number of elements (length)

In Python 2.7, 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:
>>> 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, 7.5]
like image 582
LondonRob Avatar asked Nov 20 '14 15:11

LondonRob


People also ask

How do I make an equally spaced list in Python?

In order to generate evenly spaced elements, you can use the numpy. arange() method. Note: The numpy. arange() method functions by creating an array of elements with evenly spaced intervals.

How do you make a list of numbers between two values in Python?

Use the range() Function to Create a List of Numbers From 1 to N. The range() function is very commonly used in Python. It returns a sequence between two numbers given in the function arguments. The starting number is 0 by default if not specified.


1 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]
like image 178
wim Avatar answered Nov 22 '22 18:11

wim