themaestro
themaestro

Reputation: 14256

Move Beginning of List Up To Index To Back in Python

Let's say I had a list:

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

Given an index, say 3, what is a pythonic way to remove everything before that index from the front of the list, and then add it to the back.

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

Upvotes: 3

Views: 1188

Answers (4)

gsoriano
gsoriano

Reputation: 406

The pythonic way it's that's sdolan said, i can only add the inline 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]

Upvotes: 1

adelbertc
adelbertc

Reputation: 7320

def foo(myList, x):
    return myList[x:] + myList[:x]

Should do the trick.

Call it like this:

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

EDIT Haha all answers are the same...

Upvotes: 2

Levon
Levon

Reputation: 143047

use the slice operation e.g.,

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

gives

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

Upvotes: 3

Sam Dolan
Sam Dolan

Reputation: 32532

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

or bring 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']

Upvotes: 4

Related Questions