Home > Backend Development > Python Tutorial > How Can I Efficiently Rotate a List in Python?

How Can I Efficiently Rotate a List in Python?

Susan Sarandon
Release: 2024-12-15 10:07:14
Original
909 people have browsed it

How Can I Efficiently Rotate a List in Python?

Efficient List Rotation in Python

Rotating a list refers to shifting its elements a specified number of positions in either direction. While the provided code using slicing is functional, there are performance improvements that can be achieved.

Using Collections.Deque

The Python standard library provides a more efficient data structure for such operations: collections.deque. Deques are optimized for performing operations like enqueue and dequeue from both ends. They also offer a dedicated rotate() method.

To utilize a deque for list rotation, follow these steps:

  1. Import the deque class: from collections import deque.
  2. Initialize a deque from the original list: items = deque(list()).
  3. To rotate the deque, use the rotate() method, specifying the number of positions to shift. Positive values shift to the right, while negative values shift to the left.
  4. Retrieve the first item from the deque using popleft() or popright() to obtain the rotated list.

Example

Consider the following example:

from collections import deque

items = deque([1, 2, 3])
items.rotate(1)        # deque == [3, 1, 2]
items.rotate(-1)       # deque returns to original state: [1, 2, 3]
item = items.popleft() # deque == [2, 3]
Copy after login

In this case, the deque starts as [1, 2, 3]. After rotating once to the right, it becomes [3, 1, 2]. Rotating back to the left restores it to its original order. Finally, removing the first item results in the deque containing [2, 3].

By using deque and its rotate() method, you can achieve efficient list rotation in Python.

The above is the detailed content of How Can I Efficiently Rotate a List in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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