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
Susan SarandonOriginal
2024-12-16 22:39:13911browse

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]

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!

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