How to Rotate a Python List Left or Right?

Susan Sarandon
Release: 2024-10-19 17:39:02
Original
841 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!