0

Suppose I have a list u = [1, 2, 3, 4, 5], and u[1:] returns [2, 3, 4, 5]. I wonder what indexing returns [2, 3, 4, 5, 1], going from the second position to the last and then the first?

1 Answers1

3

You can make a general function that does this at any point in your list, just by adding two slices. This was an intentional design as to why slicing is half-open (includes left index, but excludes right index)

def rotate(l, i):
    return l[i:] + l[:i]

>>> u = [1, 2, 3, 4, 5]

>>> rotate(u, 1)
[2, 3, 4, 5, 1]
>>> rotate(u, 2)
[3, 4, 5, 1, 2]
Community
  • 1
  • 1
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218