Home > Backend Development > Python Tutorial > How Can Python's `collections.deque` Optimize List Rotation?

How Can Python's `collections.deque` Optimize List Rotation?

Susan Sarandon
Release: 2024-12-16 22:39:13
Original
910 people have browsed it

How Can Python's `collections.deque` Optimize List Rotation?

Efficient List Rotation in Python: An Alternative Approach

The provided Python code efficiently rotates a list by slicing and combining its sections. However, there exists a more optimized solution using collections.deque.

Utilizing deque's Rotate Method

deque is a data structure designed for efficient insertion and deletion at both ends. It offers a dedicated rotate() method for rotating its elements. This approach is particularly advantageous for large lists.

from collections import deque

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

In the above example:

  • Items are added to the deque using append().
  • rotate(1) rotates the deque one position to the right (clockwise).
  • rotate(-1) rotates it one position to the left (counterclockwise).
  • popleft(), like rotate(), efficiently removes an element from the left end.

The above is the detailed content of How Can Python's `collections.deque` Optimize List Rotation?. 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