Batu Lab NotesPractical developer guides

Rotate an on-call sequence without rebuilding a list

By Batu · English technical notes

Also published in our Blogger archive.

Rotate an on-call sequence without rebuilding a list

Author: Batu. AI assistance was used to draft this article.

An on-call order is a cyclic queue: after the current service finishes its turn, the next service becomes first and the previous first entry moves to the end. Store that order in collections.deque and call rotate(-1). A negative argument rotates left, so service-a moves from the front to the back and service-b becomes the next assignment. The example retains the deque’s id before rotation and asserts it is unchanged, demonstrating that the recipe mutates the same deque object rather than assigning a newly built list.

Use rotate(1) to move one position in the other direction; here it restores the original sequence. Larger positive or negative values advance or rewind by multiple positions. Reading on_call[0] obtains the current first entry after the rotation, while list(on_call) is used only to display and assert the order.

rotate() changes the shared deque, so callers holding that object observe the new scheduling state. It does not coordinate acknowledgements, availability, or concurrent scheduling decisions; production handoff rules still need suitable synchronization and persistence. A deque also favors end operations: accessing an item near its middle is slower than access at either end. For random-access roster editing, a list may be a better separate representation.

Source: Python deque.rotate() documentation.

from collections import deque

on_call = deque(["service-a", "service-b", "service-c"])
queue_identity = id(on_call)

on_call.rotate(-1)
assert id(on_call) == queue_identity
assert list(on_call) == ["service-b", "service-c", "service-a"]

print("next:", on_call[0])
print("order:", ",".join(on_call))

on_call.rotate(1)
assert list(on_call) == ["service-a", "service-b", "service-c"]
print("restored:", ",".join(on_call))

Expected stdout

next: service-b
order: service-b,service-c,service-a
restored: service-a,service-b,service-c