Search code examples
listshift

Best way to shift a list in Python?


I have a list of numbers, let's say :

my_list = [2, 4, 3, 8, 1, 1]

From this list, I want to obtain a new list. This list would start with the maximum value until the end, and I want the first part (from the beginning until just before the maximum) to be added, like this :

my_new_list = [8, 1, 1, 2, 4, 3]

(basically it corresponds to a horizontal graph shift...)

Is there a simple way to do so ? :)


Solution

  • Apply as many as you want,

    To the left:

    my_list.append(my_list.pop(0))
    

    To the right:

    my_list.insert(0, my_list.pop())