ADVERTISEMENTS

How to rotate array in python

In Python, an array is a data structure that holds a collection of elements, which can be of any data type. Python does not have a built-in array data type, but it has several modules, such as the array module, that provide array functionality. There are several ways to rotate an array, depending on the desired rotation direction and the specific needs of the application. Here are a couple of examples:

Using slicing

numbers = [3, 6, 1, 8, 2, 9]
n = 3 # number of rotations
numbers = numbers[n:] + numbers[:n]
print(numbers)  # [8, 2, 9, 3, 6, 1]

Here, we use slicing to split the array into two parts: the first n elements and the rest of the elements. Then, we concatenate these two parts to create the rotated array.

Using collections.deque

from collections import deque
numbers = [3, 6, 1, 8, 2, 9]
n = 3 # number of rotations
numbers = deque(numbers)
numbers.rotate(n)
numbers = list(numbers)
print(numbers)  # [8, 2, 9, 3, 6, 1]

Here, we first convert the list to a deque, then use the rotate method to rotate the elements, and then convert the deque back to a list.

Using Numpy

import numpy as np
numbers = np.array([3, 6, 1, 8, 2, 9])
n = 3 # number of rotations
numbers = np.roll(numbers, n)
print(numbers)  # [8, 2, 9, 3, 6, 1]

Here, we first convert the list to a numpy array and then use the roll method to rotate the array

Python is a high-level, interpreted programming language that is widely used for web development, scientific computing, data analysis, artificial intelligence, and more. It is known for its easy-to-read syntax and ability to handle a wide variety of programming tasks with minimal code. You can learn python from our Python Tutorials and Python Examples

ADVERTISEMENTS