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

Barbara Streisand
Release: 2024-10-19 17:37:02
Original
172 people have browsed it

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

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

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

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!

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!