How to rotate a list in Python?

Sometimes, we want to rotate a list in Python.

In this article, we’ll look at how to rotate a list in Python.

How to rotate a list in Python?

To rotate a list in Python, we can use the deque instance’s rotate method.

For instance, we write:

from collections import deque

items = deque([1, 2, 3])
items.rotate(1)
print(items)

We use the deque class with a list to create a deque.

Then we call rotate on it with 1 to move the last item to the first position.

Therefore, items is deque([3, 1, 2]) according to the console.

Conclusion

To rotate a list in Python, we can use the deque instance’s rotate method.