Python 101 : Generators



Iterators loop over existing elements in a list for example.

Generators generate elements as we ask for them, which helps us not overload the memory in case of big amounts of data.

Below an example or a function with a return keyword, which returns a value and exits the function:


Below is a function that returns a generator object through the yield keyword:


To get the values 'a', 'b' and 'c', we need to loop over the generator object returned by the function:

Comments

Leave as a comment:

Archive