iter() and next()
iter() turns a collection into an iterator, and next() hands you its next item each time you call it.
Used in 40 lessons of the course, from 01.01.
An iterator is an object that remembers where you are in a sequence. iter(x) builds one from a list, a string, a dict, and so on. next(it) returns the next item and moves forward one position. When nothing is left, next() raises StopIteration.
A for loop does exactly this behind the scenes: it calls iter() once, then next() until the items run out.
The difference from a list is that an iterator gets consumed: what it already handed out doesn't come back. That makes it good for delivering values one at a time.
In the course, in lesson 01.01, GenericFakeChatModel(messages=iter([...])) receives an iterator of replies. Each time the fake model answers, it asks for the next message, so each call returns a different reply, in order.
it = iter([1, 2])
next(it) # 1
Reach for it when: you need to pull values one at a time, in order, from different places in your code, or when an API asks for an iterator instead of a list.
Examples
Common mistake
it = iter(["a"]) print(next(it)) print(next(it))
Why: The iterator already gave its only item. Asking for another one when they ran out raises StopIteration.
How to write it: Pass a default value: next(it, None), or use a for loop, which stops on its own.
Common mistake
it = iter([1, 2, 3]) print(list(it)) print(list(it))
Why: The first list() consumed the whole iterator, so the second time nothing is left.
How to write it: Store the result in a variable, or create a new iterator with iter() on the original list.
