Use a custom order in range function Python

Viewed 500

I have been struggling with this quite a bit, and was wondering if there is a solution for this.

I would like to use the range(start,stop,step) function in Python, but I would like to use a different order than what the normal functionalities allow. From what I understand the range function can do 3 things:

  1. 0, 1, 2, 3 etc
  2. 10, 9, 8, 7 etc
  3. 2, 4, 6, 8 etc

Now I am looking for the following order: 0, 10, 1, 9, 2, 8, 3, 7 etc

In this case 10 in the len(df), so the last row of the df.

3 Answers

You can create a generator to do that:

def my_range(n):
    """Yields numbers from 0 to n, in order 0, n, 1, n-1..."""
    low = 0
    high = n
    while low <= high:
        yield low
        if high != low:
            yield high
        low += 1
        high -= 1
    

Some examples:

print(list(my_range(10)))
# [0, 10, 1, 9, 2, 8, 3, 7, 4, 6, 5]

for i in my_range(5):
    print(i)
    
0
5
1
4
2
3

This will provide every number in the interval exactly once, and lazily, just as range.


To answer the question in your comment:

if you want to mix the numbers in your_list = [1,3,4,5,7,9,10,12,13,14], you can just use this function to generate the indices:

your_list = [1,3,4,5,7,9,10,12,13,14]
for index in my_range(len(your_list)-1):
    print(your_list[index], end=' ')

# 1 14 3 13 4 12 5 10 7 9 

or you could build a new list in the mixed order:

new = [your_list[index] for index in my_range(len(your_list)-1)]
print(new)
# [1, 14, 3, 13, 4, 12, 5, 10, 7, 9]

range just has start, stop, step params. But you can achieve what you want by zipping two ranges together along with the chain.from_iterable function:

from itertools import chain

for val in chain.from_iterable(zip(range(11), range(10, -1, -1))):
    print(val)

# 0 10 1 9 2 8 3 7 4 6 5 5 6 4 7 3 8 2 9 1 10 0

Note this solution repeats values, if you want no repeated values, then a generator is the way to go.

To keep things simple and clear the range function cannot do this. Since it only allows to either increment or decrement at once.

but this can be achieved with loops and variables.

this is how to do it

for i in range(0,11):
    print(i,10-i,end=" ")

this code will do it.

Related