Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is a generator and how does yield work? Generator क्या है और yield कैसे काम करता है?

Answer

A generator is a function that produces a sequence of values lazily, one at a time, using yield instead of return - pausing its state between each value instead of computing everything upfront.

def count_up_to(n):
    i = 1
    while i <= n:
        yield i  # pauses here, remembers state, resumes on next call
        i += 1

gen = count_up_to(5)
print(gen)  # <generator object count_up_to at 0x...>

print(next(gen))  # 1
print(next(gen))  # 2
print(next(gen))  # 3

# Iterating a generator with a for loop (calls next() automatically)
for num in count_up_to(3):
    print(num)  # 1, 2, 3

# Generator function vs regular function - key difference
def regular_func():
    return [1, 2, 3]  # computes and returns the FULL list immediately

def generator_func():
    yield 1
    yield 2
    yield 3  # each value computed lazily, only when requested

# Once exhausted, a generator raises StopIteration and cannot be reused
gen = count_up_to(2)
next(gen)  # 1
next(gen)  # 2
# next(gen)  # StopIteration

# Memory efficiency - generators don't store all values in memory at once
def infinite_counter():
    n = 0
    while True:
        yield n
        n += 1
# This would be impossible as a regular function returning a list!

Generator एक function है जो values की sequence lazily produce करता है, एक-एक करके, return की बजाय yield इस्तेमाल करके - हर value के बीच अपनी state pause कर देता है।

def count_up_to(n):
    i = 1
    while i <= n:
        yield i  # यहां pause होता है, state याद रखता है
        i += 1

gen = count_up_to(5)
print(gen)  # generator object

print(next(gen))  # 1
print(next(gen))  # 2

# for loop से iterate करना
for num in count_up_to(3):
    print(num)  # 1, 2, 3

# Regular function vs generator function
def regular_func():
    return [1, 2, 3]  # पूरी list तुरंत return

def generator_func():
    yield 1
    yield 2
    yield 3  # हर value lazily compute होती है

# Exhausted होने पर StopIteration आता है
gen = count_up_to(2)
next(gen)
next(gen)
# next(gen)  # StopIteration

# Memory efficiency
def infinite_counter():
    n = 0
    while True:
        yield n
        n += 1

Was this answer clear?