Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python shift array

# 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]
 
PREVIOUS NEXT
Tagged: #python #shift #array
ADD COMMENT
Topic
Name
5+7 =