Introduction:
Rotating a Python list involves shifting its elements either left or right by a specified number of positions.
Method 1:
Question: How to rotate a list to the left?
Answer:
<code class="python">def rotate_left(l, n): return l[n:] + l[:n]</code>
Example:
<code class="python">example_list = [1, 2, 3, 4, 5] result = rotate_left(example_list, 2) print(result) # Output: [3, 4, 5, 1, 2]</code>
Method 2:
Question: How to rotate a list to the right?
Answer:
<code class="python">def rotate_right(l, n): return l[-n:] + l[:-n]</code>
Example:
<code class="python">example_list = [1, 2, 3, 4, 5] result = rotate_right(example_list, 2) print(result) # Output: [4, 5, 1, 2, 3]</code>
Explanation:
Both methods use slicing to create new lists:
The resulting shifted list is then formed by concatenating these slices.
The above is the detailed content of How to Rotate a Python List Left or Right?. For more information, please follow other related articles on the PHP Chinese website!