Efficient way to rotate a list in python

后端 未结 26 1143
一生所求
一生所求 2020-11-22 03:14

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]         


        
26条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 03:44

    Possibly a ringbuffer is more suitable. It is not a list, although it is likely that it can behave enough like a list for your purposes.

    The problem is that the efficiency of a shift on a list is O(n), which becomes significant for large enough lists.

    Shifting in a ringbuffer is simply updating the head location which is O(1)

提交回复
热议问题