We saw how take a simple function and using callbacks make it more general. We also saw how to create an iterator to make our code more straight-forward. This time we are going to see how to convert the plain function into a generator that, after understanding how generators work, will seem to be the most obvious solution.
Earlier we saw how callbacks can be better than plain functions, but we have other possible solutions. We can also create a possibly unbounded iterator that will go over the elements of our series making our code look even more straight-forward than the solution with the callback.
What if you need to process a series of values to answer a certain question, that you cannot store in memory as a list? For example when you read a huge file? Or if you can calculate the next value based on some of the previous values and some external information that comes to light during processing. Even a random series. Or if the series is infinite and you don't know up-front how far you need to go to find your answer.
In this article we are going to see 2 solutions:
A Generator Expression is doing basically the same thing as a List Comprehension does, but the GE does it lazily. The difference is quite similar to the difference between range and xrange.
A List Comprehension, just like the plain range function, executes immediately and returns a list.
A Generator Expression, just like xrange returns and object that can be iterated over.
Python has a built-in function called range that can easily generate a a range of whole numbers. There is another built-in function call xrange that provides the same result, but uses a lot less memory.
One of the selling points of using Node.js to write the back-end of your application is that in that case you use the same programming language in the back-end as you use in the front-end. Then it is easy to share code between the two.
Let's see how is that done.
For the solution look at the end of the article.