Home  >  Article  >  Backend Development  >  How to Rotate Python Lists Clockwise and Counterclockwise?

How to Rotate Python Lists Clockwise and Counterclockwise?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-19 17:33:30133browse

How to Rotate Python Lists Clockwise and Counterclockwise?

Rotating Python Lists

In Python, rotating a list refers to shifting its elements right or left by a specified number of positions. To accomplish this, you can utilize the following functions:

Clockwise Rotation:

<code class="python">def rotate_clockwise(l, n):
    return l[-n:] + l[:-n]</code>

Here, n represents the number of positions to rotate the list to the right. This function isolates the last n elements and places them at the beginning, effectively rotating the list clockwise.

Counterclockwise Rotation:

<code class="python">def rotate_counterclockwise(l, n):
    return l[n:] + l[:n]</code>

Similar to the previous function, this one rotates the list counterclockwise by shifting elements n positions to the left.

Example Usage:

<code class="python">example_list = [1, 2, 3, 4, 5]

rotate_clockwise(example_list, 2) # [3, 4, 5, 1, 2]
rotate_counterclockwise(example_list, 2) # [2, 3, 4, 5, 1]</code>

These functions operate on copies of the input list, ensuring that the original list remains unchanged. The arguments l and n specify the list to be rotated and the number of positions to shift, respectively.

The above is the detailed content of How to Rotate Python Lists Clockwise and Counterclockwise?. 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