Search code examples
pythonlistpython-itertoolscycle

How to slice a circular list


Suppose I have list as follow:

lst = [0,10,20,30,40,50,60,70]

I want elements from lst from index = 5 to index = 2 in cyclic order.

lst[5:2] yields [] I want lst[5:2] = [50,60,70,0,10]. Is there any simple library function to do this?


Solution

  • Simply split the slicing in two if the second term is smaller than the first:

    lst = [0,10,20,30,40,50,60,70]
    
    
    def circslice(l, a, b):
        if b>=a:
            return l[a:b]
        else:
            return l[a:]+l[:b]
        
    circslice(lst, 5, 2)
    

    output: [50, 60, 70, 0, 10]