When we use range(start, stop, step)
it returns every first element in every bin defined by step.
For example,
list(range(1, 10, 5))
returns
[1, 6]
But how can i get the last elements from every bin defined by step? I expect to get
[5, 10]
You could simply swap the values in the range function to get the reverse like so:
print(list(range(10, 0, -5)))
This returns:
[10, 5]
You could do list(range(10, 0, -5))[::-1]
to get [5, 10]
.
Or you could write your own generator function like so:
def range_end(start, end, step):
i = end
while i > start:
yield i
i -= step
print(list(range_end(1, 10, 5)))
This returns:
[10, 5]
And if you want to have it reversed simply do:
print(list(range_end(1, 10, 5))[::-1])
This returns:
[5, 10]