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?
Asked
Active
Viewed 127 times
0

Jiàn-gēng Chiōu
- 13
- 1
-
Thanks for pointing me to the previous threads – Jiàn-gēng Chiōu Dec 12 '14 at 21:53
1 Answers
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