# Topic covered
* Generators
* Iterable and Iterator in Python
* Create an Iterator Class
11.1 Generators
Generator is a function which is responsible to generate a sequence of values.
We can write generator functions just like ordinary functions, but it uses yield keyword to return values.
def simpleGeneratorFun():
yield 1
yield 2
yield 3
for value in simpleGeneratorFun():
print(value, end=' ')
# 1 2 3
x = simpleGeneratorFun()
print(list(x))
# [1, 2, 3]
Advantages of Generator Functions
- When compared with class level iterators, generators are very easy to use
- Improves
memory utilizationandperformance. - Generators are the best suitable for reading data from large number of large files
- Generators work great for web scraping and crawling.
* Saves memory
* Don't want the result immediately
* Lazy evaluation
[…] → list comprehension (eager, stores everything in memory).
We will get MemoryError in this case because all these values are required to store in the memory.