Introduction to generators

In the series of intermediate python, now we are going to discuss generators in Python. Please don’t confuse between generator and iterator. Generators are different from the iterator.

In a generator, unlike a normal function, we use yield instead of return. If in a function we are using yield then it is automatically converted to the generator. Generators have function next in order to access the next value generated from yield. As generators are not storing values in memory. Generators are also returning an iterator. So, we can iterate over iterators to access values as well.

We will see how to make generators through example.

How to make a Generator function?

next() method

Generator Comprehension

Moreover, generator use “yield” keyword and yield are only storing a current value in memory. Hence, generators are memory efficient as well.

So, this is all for generators. Hope you enjoyed learning generators.

Stay tuned for more amazing blogs on intermediate python.

Close Menu