
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Cyclically Rotate an Array by One in Python
The cyclic rotation of an array involves moving every element of the array one position forward, and the last element gets moved to the first position. For example, if the given array is [1,2,3,4] then the array after one cyclic rotation is [4,1,2,3].
In this article, we are going to learn how to cyclically rotate an array by one position using Python.
Using Python insert() and pop() Methods
The Python insert() method is used to insert or add an element at the specified index. The index value starts from zero. Following is the syntax of the Python insert() method -
arry.insert(position,element)
The Python pop() method is used to remove the item at the specified index value from an array. If no index value is provided, it will remove the last element by default. Following is the syntax of the Python insert() method -
arry.pop(index)
Example 1
Let's look at the following example, where we are going to rotate the array [1,2,3,4] by one position.
array = [1, 2, 3, 4] x = array.pop() array.insert(0, x) print(array)
The output of the above program is as follows -
[4, 1, 2, 3]
Example 2
Following is another example, where we are going to take the single element in the array and rotate it by one position.
array = [11] x = array.pop() array.insert(0, x) print(array)
The output of the above program is as follows -
[11]