Search code examples
pythonlistpython-3.xindexingsequences

Move elements in a list one position backward without mutating the original list


I want to write a function that moves the position of all elements in a list one position backwards (to the left). The only conditions are that the function should not mutate the original list, and it must return nothing. In essence, how do I go from the code I have created here:

def cycle(input_list):
   move = input_list
   move.append(move.pop(0))

...which moves every element one position backwards but mutates the original list, to one that does the same thing, but instead doesn't mutate the original list?


Solution

  • Easy task then, return a copy with the elements shifted:

    def cycle(input_list):
        return input_list[1:] + input_list[:1]