-2

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]
azro
  • 53,056
  • 7
  • 34
  • 70
norden87
  • 21
  • 6

2 Answers2

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]
Progrix
  • 36
  • 5
0

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

nTerior
  • 159
  • 1
  • 9