I have a python list and an index of an item I want to start a loop on the list starting from the element after my index. For example I have:
original_list = [1,2,3,4,5]
my_index = 2
new_list = [4,5,1,2,3]
I am trying to achieve the new list.
I have a python list and an index of an item I want to start a loop on the list starting from the element after my index. For example I have:
original_list = [1,2,3,4,5]
my_index = 2
new_list = [4,5,1,2,3]
I am trying to achieve the new list.
Just use list slicing, like this
>>> original_list, my_index = [1, 2, 3, 4, 5], 2
>>> original_list[my_index + 1:] + original_list[:my_index + 1]
[4, 5, 1, 2, 3]
Or you can use collections.deque and can use deque.rotate
.
In [70]: original_list = [1,2,3,4,5]
In [71]: import collections
In [72]: deq = collections.deque(original_list)
In [77]: deq.rotate(2)
In [78]: deq
Out[78]: deque([4, 5, 1, 2, 3])
This is another possibility:
>>> olist = [1,2,3,4,5]
>>> print [olist[n-2] for n in xrange(len(olist))]
[4, 5, 1, 2, 3]