Reputation: 147
I am new to python and want a function which produces a list that contains a number of integers i.e. [1,3,5,7....] like you can do with the range function i.e. range(1,21,2).
However instead of setting the upper limit I want to set how long the list should be, so I would state the starting point, the step and the number of integers I want in my list. Does such a function exist?
Upvotes: 2
Views: 3513
Reputation: 1121724
No, but it's pretty easy to make one:
def myrange(start, step, count):
return range(start, start + (step * count), step)
short demonstration:
>>> myrange(10, 2, 5)
[10, 12, 14, 16, 18]
>>> myrange(10, -2, 5)
[10, 8, 6, 4, 2]
In python 3 it'll return a range
object, just like the regular range()
function would:
>>> myrange(10, 2, 5)
range(10, 20, 2)
>>> list(myrange(10, 2, 5))
[10, 12, 14, 16, 18]
Upvotes: 7
Reputation: 879421
Martijn Pieter's answer is good for integers. If start
orstep
may be floats, you could use a list comprehension:
[start+i*step for i in range(count)]
Upvotes: 5