# Rotate() Method Of Deque Class In Python

rotate

rotate(n)

## Method Overview:

• rotate() method of python deque class rotates the sequence present in the deque object ‘n’ times.

• If no parameter is passed ‘n’ will have the default value of 1.

• If ‘n’ is negative rotation direction is right to left.

• If ‘n’ is positive rotation direction is left to right.

• The rotate() method does not return a copy of the deque which has the new sequence. Instead, rotation is applied on the contents of the deque object itself.

## Example 1 – Rotate the Python Deque Object positive number of times:

 import collections   # Create an empty deque object dequeObject = collections.deque()   # Add elements to the deque - left to right dequeObject.append(1) dequeObject.append(3) dequeObject.append(6) dequeObject.append(10)   # Print the deque contents print("Deque before any rotation:") print(dequeObject)   # Rotate once in positive direction dequeObject.rotate()   print("Deque after 1 positive rotation:") print(dequeObject)   # Rotate twice in positive direction dequeObject.rotate(2)   print("Deque after 2 positive rotations:") print(dequeObject)

## Output:

 Deque before any rotation: deque([1, 3, 6, 10]) Deque after 1 positive rotation: deque([10, 1, 3, 6]) Deque after 2 positive rotations: deque([3, 6, 10, 1])

The output shows that effectively 3 positive rotations applied on the sequence of elements present in the deque object.

## Example 2 – Rotate the Python Deque Object negative number of times:

 import collections   # Create a tuple sequence = (1, 2, 4, 8, 16, 32)   # Create a deque from the tuple sequenceInDeque = collections.deque(sequence)   # Print the contents of the deque object print("Deque before any rotation:") print(sequenceInDeque)   # Rotate once - in negative direction sequenceInDeque.rotate(-1)   print("Deque after 1 negative rotation:") print(sequenceInDeque)   # Rotate twice - in negative direction sequenceInDeque.rotate(-2)   print("Deque after 2 negative rotations:") print(sequenceInDeque)

## Output:

 Deque before any rotation: deque([1, 2, 4, 8, 16, 32]) Deque after 1 negative rotation: deque([2, 4, 8, 16, 32, 1]) Deque after 2 negative rotations: deque([8, 16, 32, 1, 2, 4])

The output shows that effectively 3 negative rotations applied on the sequence of elements present in the deque object.