Move top of list to index to return in Python

Let's say I have a list:

[a, b, c, d, e, f]

Given the index, let's say 3, what is the pythonic way to remove everything up to this index from the front of the list, and then add it back.

So, if I was assigned index 3, I would like to reorder the list as [d, e, f, a, b, c]

+3
source share
4 answers

use a slice operation for example

  myList = ['a', 'b','c', 'd', 'e', 'f']
  myList[3:] + myList[:3]

gives

  ['d', 'e', 'f', 'a', 'b', 'c']
+3
source
>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> 
>>> l[3:] + l[:3]
['d', 'e', 'f', 'a', 'b', 'c']
>>> 

or enter it into a function:

>>> def swap_at_index(l, i):
...     return l[i:] + l[:i]
... 

>>> the_list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> swap_at_index(the_list, 3)
['d', 'e', 'f', 'a', 'b', 'c']
+4
source
def foo(myList, x):
    return myList[x:] + myList[:x]

Gotta do the trick.

Name it as follows:

>>> aList = ['a', 'b' ,'c', 'd', 'e', 'f']
>>> print foo(aList, 3)
['d', 'e', 'f', 'a', 'b', 'c']

EDIT Haha all the answers are the same ...

+2
source

The pythonic path sdolan said, I can only add the built-in way:

>>> f = lambda l, q: l[q:] + l[:q]

so you can use like:

>>> f([1,2,3,4,5,6], 3)
[4, 5, 6, 1, 2, 3]
+1
source

All Articles