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

How to Rotate Python Lists Clockwise and Counterclockwise?

Patricia Arquette
Release: 2024-10-19 17:33:30
Original
267 people have browsed it

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

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

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

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!

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