Shifting Lists in Python: Rotation Right and Left
Question:
How can you rotate a Python list by a specified number of positions, either to the right or left?
Answer:
The following function accomplishes this task:
<code class="python">def rotate(l, n): return l[-n:] + l[:-n]</code>
Explanation:
Alternative Implementation:
For a more conventional rightward shift, use this function:
<code class="python">def rotate(l, n): return l[n:] + l[:n]</code>
Example:
Consider the example list [1, 2, 3, 4, 5].
<code class="python">rotate([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2]</code>
Additional Notes:
The above is the detailed content of How to Rotate a Python List Right or Left by Specified Positions?. For more information, please follow other related articles on the PHP Chinese website!