Generators In Python.

Alwaz Qazi
2 min readAug 16, 2020

No no I’m not talking about those power generators here I’m talking about Generators in Python. “Generators” by the name itself refers “to generate something” hence, their functionality is no different, they also work as Iterators in python.

Iterators are used when we want to print or fetch one value at a time. Let’s say if we have a list of 100 elements and we want to fetch value one by one then what make sense is to use Iterators.

But there are some issues with using Iterators that we have to define two methods next() and iterator() Of course, we don’t want that, we want Python to do that for us.

That is where Generators come in handy. Basically generators will give you Iterators.

lets see how to create generator.

def count_Down():       """Output 5
i=5 4
while i > 0: 3
yield i 2
i -= 1 1"""
for i in countdown():
print(i)

You might see that generators look and work the same way as functions but the only difference is functions use return keyword to return a value whereas generators use yield keyword, the yield keyword is what make a function a generator. Secondly, return keyword terminates the program whereas yield don’t.

Now, the question arises if functions and generators have similar functionality then why do we even use them , we were good with functions then why generators?.

Here is the answer to all of your queries.

The first and the foremost advantage of Generators over Iterators or functions is Memory Saving.

Let’s say you are fetching thousand records from a database and maybe you don’t want them all at a time but one at a time but still these thousand record data will be stored in your memory occupying a lot of space and you definitely don’t want that. In that case you can use Generator to fetch one value at a time and not the entire list.

This was all about Generators in Python. I’ll come up with another topic soon.

--

--