Is there a python function that loops a list to beginning? I.e:
mylist = [3,4,9,2,5,6]
mylist[4:1]
output: [5,6,3]
There is not such function in python but as a pythonic way you can use cycle
and islice
functions from itertools
module :
>>> mylist = [3,4,9,2,5,6]
>>>
>>> from itertools import cycle
>>> from itertools import cycle,islice
>>> c=cycle(mylist)
>>> list(islice(c,4,7))
[5, 6, 3]
You can also create a custom function based on your aim. for example :
>>> def slicer(li,start,end):
... c=cycle(li)
... if end<start:
... return islice(c,start,end+6)
... else:
... return islice(c,start,end)
...
>>> list(slicer(mylist,4,1))
[5, 6, 3]
>>> list(slicer(mylist,4,2))
[5, 6, 3, 4]
>>> list(slicer(mylist,4,10))
[5, 6, 3, 4, 9, 2]