Efficient way to rotate a list in python

后端 未结 26 1617
一生所求
一生所求 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:49

    This also depends on if you want to shift the list in place (mutating it), or if you want the function to return a new list. Because, according to my tests, something like this is at least twenty times faster than your implementation that adds two lists:

    def shiftInPlace(l, n):
        n = n % len(l)
        head = l[:n]
        l[:n] = []
        l.extend(head)
        return l
    

    In fact, even adding a l = l[:] to the top of that to operate on a copy of the list passed in is still twice as fast.

    Various implementations with some timing at http://gist.github.com/288272

提交回复
热议问题