Saturday, 31 December 2016

What is Generator in Python?

The object returned by range() is known as generator.

Instead of storing the entire range, [0,1,2,..,9], in memory, the generator stores a definition "for i in range(20): and computes the next value only when needed ( lazy-evaluation).
Generators are iterators because they implement the iterator protocol, so you can iterate over them.

Essentially, a generator allows you to return a list like structure, but here are some differences:

1.A list stores all elements when it is created. A generator generates the next element when it is needed.
2.A list can be iterated over as much as you need, a generator can only be iterated over exactly once.
3.A list can get elements by index, a generator cannot .It only generates values once, from start to end.(It's because they do not store all the values in memory, they generate the values on the fly)

Generator uses Yield keyword:
Yield is a keyword that is used like return, except the function will return a generator.