+ 1
Learning how to rotate numbers in Python
What is the best way to explain this code? I'm learning about slice notation in python and I'm studying hard to explain my code. Please nice comments only. def rotate_list_right(data, amount): return data[-amount:] + data[:-amount] print(rotate_list_right([1,2,3,4,5,6,7,8,9],1)) # [9, 1, 2, 3, 4, 5, 6, 7, 8] print(rotate_list_right([1,2,3,4,5,6,7,8,9],5)) # [5, 6, 7, 8, 9, 1, 2, 3, 4] print(rotate_list_right([1,2,3,4,5,6,7,8,9],9)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
4 Respostas
+ 12
Chris ,
just to mention that there is a python module that can handle the rotation of collections (like lists), also *right shifting* or *left shifting*.
> we need to import 'collections'
> the required method is .rotate(). the steps to rotate are given as an argument (integer value).
> using a positive number is rotating to the *right*, using a negative number is rotating to the *left*.
import collections
lst = [1, 2, 3, 4, 5]
de = collections.deque(lst)
de.rotate(1)
print(list(de))
# result: [5, 1, 2, 3, 4]
+ 8
The slice is a part of the list, specifying the starting and ending index positions (and optionally the direction and step, but let's ignore that for now)
list[start:end]
--> means a part of the list that contains the start index, but doesn't contain the end index.
Negative index in a list means counting from backwards, the first element is data[0] and the last element is data[-1].
data[-5:]
--> means a slice of the last 5 list elements, because the start index is the fifth element from the back, and the end is not restricted.
data[:-5]
--> means a slice of everything except the last 5 elements. Here the start is not specified so implicitly 0, and the ending index (that is no longer included in the slice) is the fifth element from the back.
So if you add these two slices you shift the specific number of elements from the end to the beginning.
It's like you have a strip of paper, you cut it in the middle and shift their positions between left and right.
+ 3
Tibor! You explained it so well. Thank you.
+ 1
Lothar!
That is a good explained as well. Im still researching other ways to rotate a list. I will keep way you wrote in mind.