Python rotate()
The rotate() method of Python’s collections.deque rotates the elements in the deque by the specified number of steps. If the number is positive, elements move from right to left (the rightmost elements move to the beginning). If the number is negative, elements move from left to right (the leftmost elements move to the end).
Syntax
deque.rotate(n)
Parameters:
n: The number of steps to rotate the deque. Positive values rotate to the right, negative values rotate to the left.
Return value:
This method rotates the deque in place and returns None. The original deque is modified directly.
Example 1: Rotating Days of the Week to the Right
This example demonstrates rotating a deque of weekdays two steps to the right:
from collections import dequedays = deque(["Mon", "Tue", "Wed", "Thu", "Fri"])days.rotate(2)print(days)
The output of this code is:
deque(['Thu', 'Fri', 'Mon', 'Tue', 'Wed'])
Example 2: Rotating Movie Titles to the Left
This example showcases rotating a deque of movie titles one step to the left:
from collections import dequemovies = deque(["Inception", "Avatar", "Interstellar", "Tenet"])movies.rotate(-1)print(movies)
The output of the code is:
deque(['Avatar', 'Interstellar', 'Tenet', 'Inception'])
Codebyte Example: Opposite Rotations
The following example illustrates rotating two deques in opposite directions within one program:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours