'Last element in every bin defined by 'step' in range

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]


Solution 1:[1]

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]

Solution 2:[2]

You can adjust the values of your range function.

Using

list(range(5, 11, 5))

You can get your desired result.

Explanation

The range function takes up to 3 arguments: start, end and step and will return a range object (which you can convert to a list).

  • The created list (using list(...)) will start with the value you set as the start argument in your range call.

  • The argument end is the element on which the list stops, but it is NOT included in the list.

  • step is self-explanatory I think

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Progrix
Solution 2 nTerior