To understand what Show IterablesWhen you create a list, you can read its items one by one. Reading its items one by one is called iteration:
Everything you can use " These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values. GeneratorsGenerators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly:
It is just the same except you used
Yield
Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once. To master Then, your code will continue from where it left off each time Now the hard part: The first time the Your code explainedGenerator:
Caller:
This code contains several smart parts:
Usually, we pass a list to it:
But in your code, it gets a generator, which is good because:
And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question... You can stop here, or read a little bit to see an advanced use of a generator: Controlling a generator exhaustion
Note: For Python 3, use It can be useful for various things like controlling access to a resource. Itertools, your best friendThe itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator? Chain two generators? Group values in a nested list with a one-liner? Then just An example? Let's see the possible orders of arrival for a four-horse race:
Understanding the inner mechanisms of iterationIteration is a process implying iterables (implementing the There is more about it in this article about how |