26. A Re-iterable Date Range
Difficulty: Medium · Topic: Generators & iterators
Backfills loop over dates. Write a class DateRange(start, end, step_days=1) over datetime.date values from start to end inclusive:
- It can be iterated any number of times, including in nested loops over the same object.
len()gives the number of dates. Whenendis beforestartthe range is empty.step_daysbelow 1 raisesValueErrorwhen the range is created.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
from datetime import date
[d.isoformat() for d in DateRange(date(2026, 1, 30), date(2026, 2, 2))]Expected: ['2026-01-30', '2026-01-31', '2026-02-01', '2026-02-02']
Hints
Hint 1
An iterable returns a new iterator from__iter__ each time; an iterator returns itself and is used up after one pass.Hint 2
Writing__iter__ as a generator (with yield) gives a fresh iterator on every call.Hint 3
datetime.timedelta(days=n) steps a date.Learn the concepts
- Files, JSON, CSV and dates · 8 min read. Read files line by line, JSON and CSV, ISO dates, strptime codes, time zones and zoneinfo.
- Iterators, yield from and itertools · 8 min read. The iterator protocol, re-iterable classes, recursive generators and the itertools you will use.
More Python problems
- Read a File in Chunks · Easy
- Batch an Iterable · Easy
- A Generator Pipeline · Medium
- Moving Average over a Stream · Medium
- Flatten Any Iterable Lazily · Medium
- Merge Sorted Streams Lazily · Hard