Home >Backend Development >Python Tutorial >How to Rotate a Python List Left or Right?

How to Rotate a Python List Left or Right?

Susan Sarandon
Susan SarandonOriginal
2024-10-19 17:39:021086browse

How to Rotate a Python List Left or Right?

Python List Rotation

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:

  • Left Rotation: The l[n:] slice includes elements from the nth position to the end, while l[:n] includes elements from the beginning to the nth position.
  • Right Rotation: The l[-n:] slice includes elements from the last n positions of the list, while l[:-n] includes elements from the beginning to the second-to-last nth position.

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!

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