A Peekable, Pushback Iterator

medium
Unit 19 · Rate Limiting0/3 to milestone

Parsers often need to look at the next item without consuming it. Build a wrapper around any iterable.

Implement a class Peekable(iterable) that is itself an iterator (supports iter() and next()), with:

  • peek(default=...): return the next item without consuming it. If exhausted, return default if given, otherwise raise StopIteration.
  • peek_n(n): a list of up to the next n items, without consuming them
  • push(item): put an item back, so it's returned by the next next() (last pushed, first out)
  • __bool__: True if there are items left

It must work on one-shot iterators like generators, and must not read further ahead than needed.

#iterators#classes#parsing2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
A Peekable, Pushback Iterator · TechGradify