0

I need to take a list of any length and shift it by some integer value. In this particular application, the list can be considered "cyclic" such that a shift of 1 to the right would result in the last value ending up at the first value.

This is the best I've got to (much better than all of my variants containing for loops),and it seems to work, but I wonder if there is something faster, particularly as these lists get very long.

def shift(p, U):
    U = -(U % len(p))
    q = p[U:]+p[:U]
    return q
Chris
  • 9,603
  • 15
  • 46
  • 67
  • I don't think you can make it any faster. – piokuc Mar 16 '13 at 22:55
  • 1
    http://docs.python.org/2/library/collections.html#collections.deque.rotate – A. Rodas Mar 16 '13 at 22:56
  • @martijn, it is a duplicate. My apologies... I didn't see that in my search. – Chris Mar 16 '13 at 22:59
  • Instead of moving elements around, you might want to consider wrapping the list in an object that would present a rotated *view* onto the list. This may or may not work well depending on your use case. – NPE Mar 16 '13 at 23:01

0 Answers0