yieldEasy Examples

Pauses a generator function and produces a value to the caller

Generator functions

Using yield to create lazy sequences.

python
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for num in countdown(5):
    print(num, end=" ")
print()

# Generators are lazy - values computed on demand
def squares(limit):
    i = 0
    while i < limit:
        yield i ** 2
        i += 1

print(list(squares(6)))
Expected Output
5 4 3 2 1 
[0, 1, 4, 9, 16, 25]

yield pauses the function and returns a value. When next() is called again, execution resumes after the yield. This creates lazy sequences that compute values on demand.

Want to try these examples interactively?

Open Easy Playground