Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Python
  3. Question
Python

Efficient way to rotate a list in python

Asked by Arun Singh Apr 14, 2021 1.6K views 1 answer
Share

About this question

 What is the most efficient way to rotate a list in python? Right now I have something like this:

>>> def rotate(l, n):
     return l[n:] + l[:n]
>>> l = [1,2,3,4]
>>> rotate(l,1)
[2, 3, 4, 1]
>>> rotate(l,2)
[3, 4, 1, 2]
>>> rotate(l,0)
[1, 2, 3, 4]
>>> rotate(l,-1)
[4, 1, 2, 3]

Is there a better way?

Your answer

1 Answer

More Python discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Python Blogs

Guides, tips and career advice on Python from JanBask experts.