Sometimes, we want to do list rotation with Python.
In this article, we’ll look at how to do list rotation with Python.
How to do list rotation with Python?
To do list rotation with Python, we can use list slicing.
For instance, we write
def rotate(l, n):
return l[n:] + l[:n]
to create the rotate
function that rotates list l
for n
positions.
In it, we get the slice of the array from index n
to the end of the array.
And we append the list l
from index 0 to the index n - 1
after the first list slice.
Conclusion
To do list rotation with Python, we can use list slicing.