Python: Rotate a deque for round-robin selection
collections.deque.rotate(-1) moves the first item to the back. Selecting the front and then rotating gives a simple round-robin order for a fixed, nonempty collection.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as queue_rotation.py in an empty working directory:
from collections import deque
workers = deque(["alpha", "beta", "gamma"])
alias = workers
selected = []
for _ in range(4):
selected.append(workers[0])
workers.rotate(-1)
print("Selected:", selected)
print("Next order:", list(workers))
print("Alias sees rotation:", alias is workers and list(alias) == list(workers))
workers.rotate(1)
print("One step right:", list(workers))Run it without -O so any assertions remain enabled:
python3 queue_rotation.pyCaptured output:
Selected: ['alpha', 'beta', 'gamma', 'alpha']
Next order: ['beta', 'gamma', 'alpha']
Alias sees rotation: True
One step right: ['alpha', 'beta', 'gamma']Four selections visit alpha, beta, gamma, then alpha again. Rotation mutates the same deque, so an alias observes the new order. A positive step rotates right and reverses the last left rotation in this example.
Limits and cleanup
Reading index zero requires a nonempty deque. This code selects names only; it does not execute jobs or coordinate concurrent consumers. If other code can modify the queue, protect the combined selection and rotation according to your application’s synchronization rules.
After testing, remove the example script from its working directory:
rm -- queue_rotation.pyReference
Acknowledgements
This post was created with assistance from AI.