-1

How can i create a list of numbers that it will be a serie? for example function(0, 2, 5) from 0 to 2 with 5 elements --> [0, 0.5, 1, 1.5, 2] Is there any function in python which can do it?

Tephs
  • 11
  • 3
  • range function only works with integers – Tephs Jan 18 '20 at 23:40
  • You can create a generator or a list comprehension or a regular iterator that populates your list based on the rules you define. – dmitryro Jan 18 '20 at 23:42
  • if you're not opposed to using 3rd party libraries, this has already been solve by `numpy` as shown [here](https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html#numpy.arange) – gold_cy Jan 18 '20 at 23:45

2 Answers2

3

numpy does what you want:

>>> import numpy as np
>>> np.linspace(0, 2, 5)
array([0. , 0.5, 1. , 1.5, 2. ])

If you really need it to be a list, then you can do:

>>> list(np.linspace(0, 2, 5))
[0.0, 0.5, 1.0, 1.5, 2.0]
Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52
0

This is a simple function that calculates the delta and create an array.

def n_spaced_range(x_start, x_end, n_elements):
    d = (x_end - x_start) / (n_elements-1)
    return [x_start + i*d for i in range(n_elements)]
Lior Cohen
  • 5,570
  • 2
  • 14
  • 30