"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Rotate a List in Python?

How to Rotate a List in Python?

Published on 2024-11-01
Browse:868

How to Rotate a List in Python?

Python List Rotation

The Python programming language offers numerous methods for manipulating lists, including the task of rotating its elements. Rotation involves shifting each element of a list by a specified number of positions in a specified direction, either to the right or left.

A simple and efficient approach to list rotation in Python is through slicing and concatenation. The following code defines a function that performs this operation:

def rotate(l, n):
    return l[-n:]   l[:-n]

In this function, l represents the input list, and n indicates the number of positions to rotate. The function first creates two new lists using slicing: l[-n:] and l[:-n]. The former captures the elements at the end of the list, while the latter captures the remaining elements. The two lists are then concatenated to achieve the desired rotation.

For instance, consider the Python list l below:

l = [1, 2, 3, 4, 5]

If we wish to rotate l one position to the right, we would call rotate(l, 1):

rotated_l = rotate(l, 1)
print(rotated_l)  # Output: [2, 3, 4, 5, 1]

In this example, the first element of the original list is shifted to the end, resulting in the output list [2, 3, 4, 5, 1].

The rotate function can also handle negative values of n, which indicates rotation to the left. Using a negative n, the elements are moved to the right instead of the left.

rotated_l = rotate(l, -1)
print(rotated_l)  # Output: [5, 1, 2, 3, 4]

In this case, l is rotated one position to the left, moving the last element to the front.

It is important to note that the rotate function does not modify the input list l. Instead, it creates a new list with the rotated elements. This behavior aligns with Python's immutable list design, where modifying the original list is discouraged.

Release Statement This article is reprinted at: 1729330517 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3