DEV Community

Discussion on: What is generator in python?

Collapse
 
nestedsoftware profile image
Nested Software • Edited

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.