A dashboard wants only some trades from a price feed (say, above a size threshold). Wrap the feed in an iterator that hands out only the items a test function accepts, in order.
Implement class FilterIterator:
FilterIterator(source, keep):sourceis any iterable (possibly infinite);keep(item) -> booldecides what's wanted.has_next() -> bool: is another wanted item left? It may read ahead, but repeated calls must not skip anything.next(): return the next wanted item, or raiseStopIteration.iter(it)returnsitand__next__works likenext(), soforandlist()work.
Items can be anything, including None, 0 or "". Lazy: keep runs exactly once per item read, and reading stops as soon as the next wanted item is found. Once exhausted, it stays exhausted.
⭐ Bonus: a speed test with 300,000 items earns a star at O(1) work per item read.
it = FilterIterator([4, 7, 10, 3, 8], lambda x: x % 2 == 0)
it.has_next() # True
it.has_next() # True (still 4 waiting)
it.next() # 4
it.next() # 10
list(it) # [8]
it.has_next() # False
import itertools
sq = FilterIterator(itertools.count(1), lambda n: int(n ** 0.5) ** 2 == n)
[sq.next() for _ in range(4)] # [1, 4, 9, 16]
list(FilterIterator([0, None, "", 5], lambda v: not v)) # [0, None, ""]
Show hint
a one-item buffer plus a separate "buffer is full" flag (a None sentinel breaks when None is a real item). has_next() fills the buffer; next() calls has_next(), then empties it.