Python - How To Shift or Rotate an Array in Python

ID : 465

viewed : 204

Tags : PythonPython Array

vote vote

92

This article will explain how to shift or rotate an array in the left or right direction in Python. Rotating an array means that we move or shift each value of the array towards the left or right side by n positions. And right or left-most elements move to the other end of the array.

We can shift or rotate an array in Python using various methods explained below.

Shift Array in Python Using the collections Module

We can use the deque.rotate(n) method of the collections module to rotate an array in Python. The deque.rotate(n) method rotates the deque class object n positions, where the sign of n indicates whether to rotate the deque in the left or right direction.

If the value of n is positive, then the input will be rotated from the left to right direction, and if the n is negative, the input will be rotated from the right to left direction. The code below demonstrates how to rotate an array using the deque.rotate(n) method in Python.

from collections import deque  myarray = deque([1, 2, 3, 4, 5, 6]) myarray.rotate(2) #rotate right print(list(myarray)) myarray.rotate(-3) #rotate left print(list(myarray)) 

Output:

[5, 6, 1, 2, 3, 4] [2, 3, 4, 5, 6, 1] 

Shift Array in Python Using the numpy.roll() Method

The numpy.roll(array, shift, axis) method takes the array as input and rotates it to the positions equal to the shift value. If the array is a two-dimensional array, we will need to specify on which axis we need to apply the rotation; otherwise, the numpy.roll() method will apply the rotation on both axes.

Just like the deque.rotate() method, the numpy.roll() also rotates the array from right to left if the value is positive and right to left if the value is negative. The below example code demonstrates how to rotate an array in Python using the numpy.roll() method.

import numpy as np  myarray = np.array([1, 2, 3, 4, 5, 6]) newarray = np.roll(myarray, 2) #rotate right print(newarray) newarray =np.roll(myarray, -2) #rotate left print(newarray) 

Output:

[5 6 1 2 3 4] [3 4 5 6 1 2] 

Shift Array in Python Using the Array Slicing

We can also implement the rotate function using the array slicing in Python. This method does not need any additional library but is less efficient than the methods explained above.

The below example code demonstrates how to use the array slicing to rotate or shift an array in Python.

def rotate(input, n):     return input[n:] + input[:n]  myarray = [1, 3, 5, 7, 9] print(rotate(myarray, 2)) #rotate left print(rotate(myarray, -2)) #rotate right 

Output:

[5, 7, 9, 1, 3] [7, 9, 1, 3, 5] 

  • Related HOW TO?