+1 vote
in Programming Languages by (26.1k points)
I want to move the first n elements of a list to the last of the list. Is there any function that I can use for it?

E.g.

a=[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14]

after making the first 5 elements the last 5 elements:

a=[ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14,  0,  1,  2,  3,  4]

1 Answer

+3 votes
by (33.0k points)
selected by
 
Best answer

You can use the NumPy function roll(). It rolls array elements along a given axis.

numpy.roll(a, shift, axis=None)

For moving the first n elements to the last, you need to use -n as the shift.

Here is an example for moving 5 elements:

>>> import numpy as np

>>> x=np.arange(15)

>>> x

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])

>>> np.roll(x,-5)

array([ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14,  0,  1,  2,  3,  4])

>>> 


...