create and use generators in python

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.py
def even_numbers():
    num = 0
    while True:
        yield num
        num += 2
83 chars
6 lines

This generator function can be used to generate even numbers by calling the next() function on the generator object:

main.py
even_gen = even_numbers()
print(next(even_gen))  # Output: 0
print(next(even_gen))  # Output: 2
print(next(even_gen))  # Output: 4
131 chars
5 lines

You can also iterate through the generator using a for loop:

main.py
for num in even_numbers():
    if num >= 10:
        break
    print(num)
74 chars
5 lines

The output of this code will be:

main.py
0
2
4
6
8
10 chars
6 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