Categories
Python Answers

How to do list rotation with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *