I am new in python programming. Did not understand generators even after reading some tutorials. Can someone please explain me generators in simple words with some examples?
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (2)
You can think of it as a special function that can return values repeatedly (i.e. more than once), usually in a loop. Instead of the
return
keyword,yield
is used for this purpose.I think the main use case for generators in python is as a substitute for lists. When you've got a list, that means you need to keep all of the items in the list in memory the whole time that you're using the list. Replacing a list with a generator means you just need to keep the current value in memory. The concept is very similar to an iterator, but the syntax is shorter/cleaner. Python also has generator expressions, which have a syntax very similar to list comprehensions. The difference is that a list comprehension creates a (potentially large) list in memory, whereas the generator expression only ever holds a single item in memory at a time.
A generator is a compact way of expressing a particular sequence of items as a function.
The most important aspects are:
for...in
loop, but there are many others (for example themap()
builtin function)The important part of a generator is the
yield
statement. Each time whatever is iterating over the generator asks for the next item in the sequence, the generator function is run up until the nextyield
statement is encountered, then the value provided to that statement is returned s the next item in the sequence. The key point to understand here is that after this, the generator function is 'paused' until the next time the generator gets asked for a new item. When an item is asked for again, the generator function resumes execution from exactly where it was previously, retaining the values that any variables local to the generator function had previously.Further explanation will require some code, so here's an example:
This is a trivial generator function that will spit out the terms of the Fibonacci sequence. There's no termination condition, so if you were to loop over it, it the loop would just keep going forever.
Assume we start looping over this generator like so (don't do this unless you want to have to manually kill the Python interpreter, it will loop forever):
The overall execution flow will look like this:
current
as the next item.x
equal to to the value ofcurrent
.