easy +10 pts

Custom iterator class

Build an iterator that cycles through a list forever, with a stop limit.

Define a class `CyclicIterator` that implements the iterator protocol. The class is initialized with two arguments: `items` (a non-empty list) and `limit` (an integer >= 0). When iterated, it yields elements from `items` cyclically (i.e., after the last element, it goes back to the first) until the total number of yielded elements reaches `limit`. If `limit == 0`, iteration yields nothing. The iterator must raise `StopIteration` naturally when exhausted. Implement the `__iter__` method returning `self`, and `__next__` method that returns the next element or raises `StopIteration` when the limit is reached. **Function signature:** ```python class CyclicIterator: def __init__(self, items, limit): ... def __iter__(self): ... def __next__(self): ... ```

Constraints

items is a non-empty list of any hashable? No, just any objects. `limit` is a non-negative integer. The list must not be modified during iteration. Time complexity per `__next__` call is O(1). Maximum `limit` fits within memory.

Example

>>> it = CyclicIterator([1, 2, 3], 3)
>>> list(it)
[1, 2, 3]
>>> it = CyclicIterator(['a', 'b'], 5)
>>> list(it)
['a', 'b', 'a', 'b', 'a']
>>> it = CyclicIterator([True, False], 0)
>>> list(it)
[]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Keep track of the current index and the number of elements yielded so far.
When index reaches len(items), reset it to 0.
In __next__, if count >= limit, raise StopIteration.
Remember to return self from __iter__.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.