In Python, a generator is a type of iterator that allows generating values on-the-fly without creating a full list in memory. This means that generators are memory efficient and can handle large data sets easily. Generators are created using the yield
keyword.
Here's an example of creating a generator that generates even numbers using an infinite loop and yield
:
main.py83 chars6 lines
This generator function can be used to generate even numbers by calling the next()
function on the generator object:
main.py131 chars5 lines
You can also iterate through the generator using a for loop:
main.py74 chars5 lines
The output of this code will be:
main.py10 chars6 lines
In this example, the generator will generate even numbers indefinitely until the for loop is broken when the generated number is greater than or equal to 10.
gistlibby LogSnag