Loading topic
for loops work, how generators behave, and why some loops silently produce nothing the second time. This5 min readtry/except works. Everything Python does when it loops over data rests on a small contract called the iterator protocol. This chapter covers t5 min readiter() and next() exist and that a class can define __iter__ and __next__. It also assumes you are comfortable with try/except. Here you will see how for uses those pieces, so you can predict its behavior in edge cases.5 min read__init__ and other special methods, and that you know the idea behind the iterator protocol from the previous chapters: iter() produces an iterator, and next() pulls values from it until StopIteration. Here you implement that protocol yo5 min readtry/except works. You should also know the iterator protocol from the earlier chapters: iter() returns an iterator, next() pulls a value, and StopIteration marks the end. If you have written a class with __iter__ and __next__,5 min readyield and that you know how next() and StopIteration work in the iterator protocol. Here you will trace what happens inside a generator from the moment you call it until it is finished. You will also see the edge cases that surprise 5 min read__iter__, __next__, StopIteration), and how a5 min readfor loops call next() on an iterator. Earlier chapters covered both. Here we look at what they buy you: lower memory use, earlier results, and streams of unbounded length. We also look at wh6 min readyield, that you know a generator expression is a lazy version of a list comprehension, and that you have seen how for loops call iter() and next(). If any of that is unclear, review the earlier chapters on generator functions and g6 min read__iter__, __next__, StopIteration) and can write generator functions and generator expressions. It covers the bugs that come from one fact: an iterator is a one-way, single-use object.5 min readitertools module is a standard-library collection of functions that build and combine iterators. Each function takes iterables a5 min readiter(callable, sentinel). It turns "call this function until it returns a stop value" into an ordinary iterator. It assumes you know how iter() and next() work on iterables, what StopIteration does, and how to write a lambda or use `functools.parti5 min readyield, know that a generator is an iterator, and understand how StopIteration ends a loop. Send, throw and return values appear only as far as yield from needs them.5 min readyield, you know that next() raises StopIteration when a generator finishes, and you have seen yield from used to delegate to another generator. Earlier chapters covered all three.5 min readsend(), throw() and close().5 min read