Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating values in a list [Python]

I understand this question has been asked before but I haven't seen any that answer it in a way without splitting the list.

say I have a list:

num = [1,2,3,4,5,6]

I want to create a function:

rotate(lst, x):

So that if I call rotate(num, 3) it will globally edit the list num. That way when I later call print(num) it will result in [4,5,6,1,2,3].

I understand that I could write the function something like:

rotate(lst, x):
    return [lst[-x:] + lst[:-x]

But I need to do this function without a return statement, and without splitting the list. What I'm thinking would work would be to put the last value of the list into a variable: q = lst[-1] and then from there create a loop that runs x amount of times that continues to move the values towards the end of the list and replacing the 0th position with whatever is stored in q.

One more thing. If I call rotate(lst, -3) then instead of rotating to the "right" it would have to rotate to the "left".

I'm new to python and having trouble wrapping my mind around this concept of manipulating lists. Thank you everyone for your time and effort. I hope this problem was clear enough.

like image 342
Kenta Avatar asked Jan 18 '26 15:01

Kenta


2 Answers

You can use slicing assignment to modify your current strategy to do what you want. You're already generating the rotated list correctly, just modify the list in place with lst[:] = ...

def rotate(lst, x):
    lst[:] =  lst[-x:] + lst[:-x]

Example in the interactive interpreter:

>>> l = [1, 2, 3, 4, 5, 6]
>>> def rotate(lst, x):
...     lst[:] =  lst[-x:] + lst[:-x]
...
>>> rotate(l, 2)
>>> l
[5, 6, 1, 2, 3, 4]

Now rotate it backwards:

>>> rotate(l, -2)
>>> l
[1, 2, 3, 4, 5, 6]
>>> rotate(l, -2)
>>> l
[3, 4, 5, 6, 1, 2]

See this answer on a different question: https://stackoverflow.com/a/10623383/3022310

like image 153
turbulencetoo Avatar answered Jan 21 '26 08:01

turbulencetoo


Here is a solution using a double-ended queue. As required, it modifies the list in place, neither uses return nor uses chunks of the list.

from collections import deque

def rotate(lst, x):
    d = deque(lst)
    d.rotate(x)
    lst[:] = d

num = [1,2,3,4,5,6]
rotate(num,3)
print(num)
rotate(num,-3)
print(num)

produces

[4, 5, 6, 1, 2, 3]
[1, 2, 3, 4, 5, 6]

Please have a look at PMOTW's tutorial on deque

like image 31
Pynchia Avatar answered Jan 21 '26 06:01

Pynchia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!