Home  >  Article  >  Backend Development  >  How to Rotate a Python List Right or Left by Specified Positions?

How to Rotate a Python List Right or Left by Specified Positions?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 17:37:02173browse

How to Rotate a Python List Right or Left by Specified Positions?

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:

  • l[-n:] creates a new list containing the last n elements from the right end of the original list.
  • l[:-n] creates a new list containing the remaining elements from the original list.
  • Concatenating these two lists ([l[-n:]] [l[:-n]]) effectively shifts the list by n positions to the right.

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 rotate function returns a new list and does not modify the input list.
  • The argument n can be negative to rotate the list to the left.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn