Generators
Generators are a very useful tool but they come with a set of rules to keep in mind.
First, let’s explore the advantages of generators:
- Generators are often simpler to write than list-generating functions. Instead of having to declare a
list
,list.append(value)
, andreturn
, you only needyield value
. - Memory usage. Items can be processed one at a time, so there is generally no need to keep the entire list in memory.
- Results can depend on outside factors. Instead of having a static list, you generate the value when it is being requested. Think of processing a queue/stack, for example.
- Generators are lazy. This means that if you’re using only the first five results of a generator, the rest won’t even be calculated. Additionally, between fetching the items, the generator is completely frozen.
The most important disadvantages are:
- Results are available only once. After processing the results of a...