how to use yield in python

In Python, a generator is a type of iterable, like lists or tuples. However, unlike lists, generators do not store their contents in memory. Instead, they generate their content on-the-fly during iteration. One way to create a generator is through the use of the yield keyword.

Here is an example of how yield can be used:

main.py
def my_generator():
    yield 1
    yield 2
    yield 3
56 chars
5 lines

This function creates a simple generator that yields 1, 2, and 3 in sequence. When we iterate over this generator, the values are generated on-the-fly:

main.py
for i in my_generator():
    print(i)
38 chars
3 lines

Output:

main.py
1
2
3
6 chars
4 lines

Notice that the my_generator function is paused after each yield statement until the next iteration is requested. This allows for lazy evaluation of the values, which can be more memory-efficient in some situations.

In summary, the yield keyword is used to create generators in Python, which allow for lazy evaluation and efficient use of memory.

gistlibby LogSnag