-3

I am looking for a function in Python, which I have used before, which takes three arguments. Let's say x and y, and stepsize. Then it will generate a list starting at x, taking steps of size stepsize and ending at y.

Example would be:

listIwant = function(20,30,2)
print(listIwant)

And then it would print:

[20 22 24 26 28 30]

Can't seem to find the function I am looking for.

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
dejoma
  • 394
  • 1
  • 6
  • 18

1 Answers1

2

I think you are looking for range, which returns a list in Python 2, but in Python 3 returns a generator. However this is easily converted to a list:

print(list(range(20,30,2)))
>>> [20, 22, 24, 26, 28]

Note: the second argument is a non-inclusive upper bound, so in order to get your desired output you would need to feed it:

print(list(range(20,31,2)))
>>> [20, 22, 24, 26, 28, 30]
iacob
  • 20,084
  • 6
  • 92
  • 119
  • Thanks, any alternative to this function for floats? – dejoma Jul 21 '18 at 14:22
  • @Dennis can you be a bit more explicit? i.e. give me an example of expected input and output? – iacob Jul 21 '18 at 14:23
  • @Dennis I don't think there's a built-in, but it wouldn't be too hard to make your own with the `yield` keyword. Try defining a function that yields a few values (like `return`, but the code carries on) and test it in a for loop. – wizzwizz4 Jul 21 '18 at 14:23
  • np.arange(0.0, 1.0, 0.1) is the function I was looking for. – dejoma Jul 21 '18 at 14:25
  • 1
    @Dennis **note:** [`np.arange`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html) returns an ndarray, not a list. – iacob Jul 21 '18 at 14:31