Consider the following simple python code
>>> L = range(3)
>>> L
[0, 1, 2]
We can take slices of this array as follows:
>>> L[1:3]
[1, 2]
Is there any way to wrap around the above array by shifting to the left
[1, 2, 0]
by simply using slice operations?
Left:
Right:
To my mind, there's no way, unless you agree to cut and concatenate lists as shown above. To make the wrapping you describe you need to alter both starting and finishing index.
No combination of these can provide the wrapping point where tail items are followed by initial items. So the entire thing can't be created.
Numerous workarounds exist. See answers above, see also
itertools.islice
and.chain
for a no-copy sequential approach if sequential access is what you need (e.g. in a loop).Rotate left
n
elements (or right for negative n):Note that collections.deque has support for rotations. It might be better to use that instead of lists.
If you are not overly attached to the exact slicing syntax, you can write a function that produces the desired output including the wrapping behavior.
E.g., like this:
Example output:
Caveat: You can't use this on the left-hand side of a slice assignment.