[Type C]Q4. Write a program that rotates the elements of a list so that the element at the first index moves to the second index, the element in the second index moves to the third index, etc, and the element in the last index moves to the first index.7. Write a program that rotates the elements of a list so that the element at the first index moves to the second index, the element in the second index moves to the third index, etc., and the element in the last index moves to the first index.Published On - July 17, 2019 Show
PythonCSIP CS IP sa 11 cs chapter 11, sa 11 ip chapter 7 Path Walla
HomeList Manipulation Python program to right rotate a list by nGiven a list, right rotate the list by n position. Examples : Input : n = 2 List_1 = [1, 2, 3, 4, 5, 6] Output : List_1 = [5, 6, 1, 2, 3, 4] We get output list after right rotating (clockwise) given list by 2. Input : n = 3 List_1 = [3, 0, 1, 4, 2, 3] Output : List_1 = [4, 2, 3, 3, 0, 1]Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach #1 : Traverse the first list one by one and then put the elements at required places in a second list. Python3
Output : [4, 5, 6, 1, 2, 3] Time complexity : O(n) Approach #2 : Another approach to solve this problem by using slicing technique. One way of slicing list is by using len() method. Python3
Output: [4, 5, 6, 1, 2, 3]Approach #3 : In the above method, last n elements of list_1 was taken and then remaining elements of list_1. Another way is without using len() method. Python
Output : [4, 5, 6, 1, 2, 3]Time complexity : O(n) Note : list_1[:] will return the whole list as the blank space on left of slicing operator refers to start of list i.e 0 and blank space on right refers to ending position of list. 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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Article Tags :
Python Technical Scripter
Python list-programs python-list Practice Tags :
python-list |