In Summary : Generators
In Summary : Generators
In summary…
Generators allow you to create iterators in a very pythonic
manner.
Iterators allow lazy evaluation, only generating the next
element of an iterable object when requested. This is useful
for very large data sets.
Iterators and generators can only be iterated over once.
Generator Functions are better than Iterators.
Generator Expressions are better than Iterators (for simple
cases only).
-----------------------------------------------------------------------------------------------------------------------------------
https://thepythonguru.com/python-generators/
Generators are function used to create iterators, so that it can be used in the for loop.
Creating Generators
Generators are defined similar to function but there is only one difference, we use yield keyword
to return value used for each iteration of the for loop. Let’s see an example where we are trying
to clone python’s built-in range() function.
4 i = start
6 yield i
7 i += step
9 try:
13 print(ex)
14 except:
Expected Output:
1 10
2 13
3 16
4 19
5 22
6 25
7 28
8 31
9 34
10 37
11 40
12 43
13 46
14 49