Python generators are simple way to create or generate iterators. They allow you to control flow and also increase the memory performance in some cases. Generators look like normal function but there is a difference in syntax and semantics between them and functions.
You can think of generators as more comfortable way to generates iterators. Let’s see how generators work –
- A generator works and being called just like a function.
- Its return value is an iterator object.
- Generator doesn’t work at the first time.
- Code is executed until the yield keyword.
- Yield function returns the value of the expression.
- Generator ensures that the performance while execution is improved.
Let’s take a look at code:
def count(): yield("one") yield("two") yield("three") yield("four") x = count() print x.next() print x.next() print x.next() print x.next()
If you execute this code then you’ll see that our iterator x that we generated here calls the next() function and returns the count one after another. If you want to see generators in action, you can use yield() inside python regular expression program.
Use of Python Generators
- Generators can be useful for calculatig large sets of results. This is the case especially when you have to loop through the results.
- Generators are also used to make the solutions of some of the problems more clear.
- In some of the programs you need a way to make a buffer in your rogram. In such case, generators can be used to process small data and it works like a buffer.
- If you use generators in your code then you’re likely to find your code more easy to read.
- For programs that require to process one value at a time can make use of the generators.
- You can also avoid the callback functions and use the yield() instead.
Generators and Performance Improvement
How generators help you improve memory? You can use them anywhere where you want to access the values one at a time. That way instead of pre-computing all the values and storing them in list or printing them, you can iterate over them one at a time. This saves a lot of your time.
I hope this small tutorial on python generators and iterators helps you.