5

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497

3 Answers3

7

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]
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
4

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])
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
0

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]
Eithos
  • 2,421
  • 13
  • 13