Skip to content
Related Articles

Related Articles

Program to cyclically rotate an array by one in Python | List Slicing
  • Last Updated : 21 Nov, 2018

Given an array, cyclically rotate the array clockwise by one.

Examples:

Input:  arr = [1, 2, 3, 4, 5]
Output: arr = [5, 1, 2, 3, 4]

We have existing solution for this problem please refer Program to cyclically rotate an array by one link. We will solve this problem in python quickly using List Comprehension. Approach is very simple, just remove last element in list and append it in front of remaining list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Program to cyclically rotate an array by one
  
def cyclicRotate(input):
       
     # slice list in two parts and append
     # last element in front of the sliced list
       
     # [input[-1]] --> converts last element pf array into list
     # to append in front of sliced list
  
     # input[0:-1] --> list of elements except last element
     print ([input[-1]] + input[0:-1])
  
# Driver program
if __name__ == "__main__":
    input = [1, 2, 3, 4, 5]
    cyclicRotate(input)

chevron_right


Output:

[5, 1, 2, 3, 4]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :