A program to rotate an array one by one in Python | Slicing list

Python Methods and Functions

Examples:

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

We have a solution to this problem, please refer to List Comphetsion . The approach is very simple, just remove the last item in the list and add it before the rest of the list.

# Program for cyclic array rotation by one

 

def cyclicRotate ( input ):

 

# list sections in two and add

  # last element before the sliced ​​list

  

# [input [-1]] - & gt; converts the last element of the pf array to a list

# add before the sliced ​​list

 

# input [0 : -1] - & gt; list of elements except the last one

print ([ input [ - 1 ]] + input [ 0 : - 1 ])

 
# Driver program

if __ name__ = = "__ main__" :

input = [ 1 , 2 , 3 , 4 , 5 ]

cyclicRotate ( input )

Output:

 [5, 1, 2, 3, 4] 





Tutorials