Skip to content

Instantly share code, notes, and snippets.

@emilamaj
Created June 14, 2023 23:10
Show Gist options
  • Select an option

  • Save emilamaj/15b3a8be12558671c5bc172812b4d83f to your computer and use it in GitHub Desktop.

Select an option

Save emilamaj/15b3a8be12558671c5bc172812b4d83f to your computer and use it in GitHub Desktop.
Python rotate/shift a sub-list along an input list
# This function rotates a sublist of a list, given a starting position and a length. Position can be incremented infinitely.
def rotateSubList(bigList, position, length):
# We check if the left index is still smaller than the right index after the modulo operation.
if position % len(bigList) < (position+length) % len(bigList):
# The order is preserved, so we can safely use the slice notation
return bigList[position%len(bigList): (position+length)%len(bigList)]
else:
# The order is NOT preserved. The resulting array would have been clamped to the right by the slice notation.
# We add the missing part, sourced from the start of the bigList.
return bigList[position%len(bigList): len(bigList)] + bigList[0: (position+length)%len(bigList)]
# For example:
# a = [0,1,3,4,5,6,7,8,9,10]
# rotateSubList(a, 3, 5) returns [4, 5, 6, 7, 8]
# rotateSubList(a, 4, 5) returns [5, 6, 7, 8, 9]
# [...]
# rotateSubList(a, 7, 5) returns [8, 9, 10, 0, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment