Python Program to Rotate Elements of a List
Lists in Python are a very useful data structure that allow you to store collections of data. However, sometimes you may need to rotate the elements in a list. This means that you want to shift each element of the list to the right or left by a certain number of places. In this article, we will explore how to rotate elements of a list in Python.
Rotating Elements of a List
The easiest way to rotate a list is to use the deque
(double-ended queue) class from the collections
module. The deque
class is a generalization of stacks and queues and allows you to rotate a list easily.
Here’s an example of rotating a list to the right:
from collections import deque
def rotate_right(lst, n):
deq = deque(lst)
deq.rotate(n)
return list(deq)
In this code, we first create a deque
object from the list lst
. We then use the rotate
method to rotate the deque n
places to the right. Finally, we convert the deque back to a list using the list
constructor and return it.
We can use this function to rotate a list to the right by any number of places:
lst = ['a', 'b', 'c', 'd', 'e']
print(rotate_right(lst, 2)) # output: ['d', 'e', 'a', 'b', 'c']
This code rotates the list lst
to the right by 2 places.
To rotate a list to the left, we simply use a negative value for n
:
def rotate_left(lst, n):
deq = deque(lst)
deq.rotate(-n)
return list(deq)
lst = ['a', 'b', 'c', 'd', 'e']
print(rotate_left(lst, 2)) # output: ['c', 'd', 'e', 'a', 'b']
This code rotates the list lst
to the left by 2 places.
Conclusion
In this article, we explored how to rotate elements of a list in Python. We used the deque
class from the collections
module to do the rotation. With this knowledge, you can now easily rotate lists of any size and number of elements.