Circular Linked List Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Circular Linked List runs in O(1) insert time and O(n) space, in Python as in every other language.
- ✓No node-based ring, but itertools.cycle covers the common case: it returns an infinite iterator over a finite iterable, which is what most round-robin code actually needs.
- ✓Prefer itertools.cycle or deque(maxlen=n) and only build real nodes when you must splice the ring at run time.
- ✓The Python trap: json.dumps on a ring raises ValueError: Circular reference detected, and it is raised only when you try to serialise, typically in a log line or a debug endpoint rather than in the code that built the structure.
- ✓itertools.cycle stores every item it has seen on the first pass, so memory grows to the full length of the source iterable even though the iterator looks constant-space.
What Circular Linked List actually is
Circular Linked List in Python: what you actually reach for
Python implementation
from itertools import cycle
from collections import deque
# Round-robin without nodes: the stdlib answer.
workers = cycle(["w1", "w2", "w3"])
assignment = [next(workers) for _ in range(5)]
# ['w1', 'w2', 'w3', 'w1', 'w2']
# A bounded ring buffer, also without nodes.
recent = deque(maxlen=3)
for line in ["a", "b", "c", "d"]:
recent.append(line)
# deque(['b', 'c', 'd'], maxlen=3)
# A real node ring, when you must splice it at run time.
class Node:
__slots__ = ("val", "next")
def __init__(self, val):
self.val = val
self.next = self # a one-element ring points at itself
class Ring:
def __init__(self):
self.cursor = None
self.size = 0 # tracked, never derived: measuring costs O(n)
def insert_after_cursor(self, val) -> None:
node = Node(val)
if self.cursor is None:
self.cursor = node
else:
node.next = self.cursor.next
self.cursor.next = node
self.size += 1
def rotate(self, steps: int = 1) -> None:
for _ in range(steps % max(self.size, 1)):
self.cursor = self.cursor.next
def to_list(self) -> list:
# Stop by count, not by looking for None: there is no None.
out, node = [], self.cursor
for _ in range(self.size):
out.append(node.val)
node = node.next
return outThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1) insert
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Circular Linked List?
No node-based ring, but itertools.cycle covers the common case: it returns an infinite iterator over a finite iterable, which is what most round-robin code actually needs. For a fixed-size overwriting buffer, collections.deque with a maxlen argument silently evicts from the opposite end and is a ring in everything but name.
What is the most common Python mistake when implementing Circular Linked List?
json.dumps on a ring raises ValueError: Circular reference detected, and it is raised only when you try to serialise, typically in a log line or a debug endpoint rather than in the code that built the structure. copy.deepcopy is safe because it keeps a memo dictionary of already-copied objects and reproduces the cycle correctly, but copy.copy gives you a shallow node whose next still points into the original ring, quietly linking two structures together.
How does Circular Linked List actually perform in Python?
itertools.cycle stores every item it has seen on the first pass, so memory grows to the full length of the source iterable even though the iterator looks constant-space. On a generator of a million rows that is a surprise. deque(maxlen=n) is genuinely bounded. Time complexity is O(1) insert and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.