Rotate an array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Rotate an array

To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to arr[1] …and finally temp to arr[n-1] Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2 Rotate arr[] by one 2 times We get [2, 3, 4, 5, 6, 7, 1] after first rotation and [ 3, 4, 5, 6, 7, 1, 2] after second rotation

18th Dec 2020, 11:43 AM
Prateek Kalwar
6 Answers
+ 2
《 Nicko 12 》 your code is right ..... Thanks
18th Dec 2020, 2:08 PM
Prateek Kalwar
+ 1
lst = [1,2,3,4,5] for i in range(2): lst.append(lst.pop(0)) print(lst)
18th Dec 2020, 12:10 PM
noteve
noteve - avatar
+ 1
《 Nicko 12 》try it for [12,34,98,33]
18th Dec 2020, 12:12 PM
Prateek Kalwar
+ 1
Prateek Kalwar Its working just fine but can you tell me whats the problem? Because I know that the code could be wrong cause its too simple, I just want to know what is wrong, for myself. Thanks!
18th Dec 2020, 12:15 PM
noteve
noteve - avatar
+ 1
Mirielle[ INACTIVE ] Oh yes, Youre right, now I noticed even though its correct it is not actually a rotation, It just return the 1st value then append it to the list(which is not a rotation). Thank you for letting me know!😊 That will help me in future codes.
19th Dec 2020, 12:07 PM
noteve
noteve - avatar
18th Dec 2020, 11:51 AM
Prateek Kalwar