yield

KeywordPython 2.0+Intermediate

Pauses a generator function and produces a value to the caller

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

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)))

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.

Try in Playground

Tags

languagesyntaxcoregeneratoriterationfunctional-programming

Related Items