Member-only story
Today when I was studying classes in Python, I read that a class is not necessary if generators are used. I had never heard of classes in Python, so I decided that perhaps I should learn about this as well.
I decided to look at Tech with Tim’s video on generators, so that is what this post is about.
Generators are related to iterators. An iterator is an object that allows a programmer to traverse a container: particularly a list.
A generator is a routine that can be used to control the iteration behaviour of a loop. A generator is very similar to a function that returns an array.
Generators use a new syntax and are easier to create than standard iterators.
When you use the range function, you do not need to store all of the elements in that data structure. The range function returns an iterator.
A map function takes some data structure and maps all of the values in the data structure to some function and returns an iterator that contains all of the results of this function called on all of these values. The map function is a generator that allows us to iterate through all of the results without storing all of the values.
The function next() gives the next value through a function of an iterator.