Categories
Python Answers

How to rotate a list in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *