← Back to Python Course | Chapter 11: Advanced Python | Lesson 2 of 12

Python Generators

Generator एक बार में एक value सिर्फ़ पूछे जाने पर बनाता है, जैसे कोई machine जो हर बार button दबाने पर एक cookie बेक करती है। यह memory बचाता है क्योंकि यह सब कुछ एक साथ नहीं बनाता।
Syntax
python
def generator_name():
    yield value1
    yield value2

for item in generator_name():
    # use item

Generator क्या है?

एक generator function दिखने में एक साधारण function जैसा है पर return की बजाय yield इस्तेमाल करता है, और उसे call करना तुरंत function body नहीं चलाता -- यह एक generator object लौटाता है जो मांगे जाने पर ही एक बार में एक value produce करता है।

उदाहरण: What is a Generator?

python
def my_gen():
    yield 1  # yield instead of return makes this a generator function
    yield 2

g = my_gen()
print(type(g))  # generator object, body hasn't run yet
print(next(g))  # runs up to the first yield

yield Keyword

हर बार yield execute होता है, function ठीक वहीं रुक जाता है, yield किया गया value लौटा देता है, और अपनी पूरी local state (variables, loops में position) याद रखता है -- next() की अगली call function को शुरू से चलाने की बजाय ठीक उस yield के बाद से resume करती है।

उदाहरण: The yield Keyword

python
def counter():
    n = 1
    while True:
        yield n  # pauses here, remembering n
        n += 1

c = counter()
print(next(c))  # first call, prints 1
print(next(c))  # second call, resumes after yield and prints 2

Generator Expressions

एक generator expression -- (x*2 for x in range(10)) -- list comprehension जैसे लगभग एक जैसे syntax से एक generator बनाता है, पर square brackets की बजाय parentheses के साथ, और results की पूरी list कभी memory में बनाए बिना।

उदाहरण: Generator Expressions

python
squares = (x * x for x in range(5))
print(list(squares))

Generator State और Lifecycle

जब कोई generator function अपने body के अंत तक चलता है या plain return statement पर पहुँचता है, तो Python अपने आप यह संकेत देने के लिए StopIteration raise करता है कि अब produce करने के लिए कुछ बचा नहीं -- यह बिल्कुल वही signal है जिसे for loop किसी भी iterator पर iterate करते समय देखता है।

उदाहरण: Generator State and Lifecycle

python
def one_value():
    yield "only value"

g = one_value()
print(next(g))
try:
    next(g)  # generator body has finished
except StopIteration:
    print("Generator exhausted")

Performance Benefits

चूँकि generator पहले से पूरी list बनाने की बजाय एक बार में एक value compute और yield करता है, यह चाहे कितनी भी values आख़िर में produce करे, हमेशा एक निश्चित, छोटी मात्रा में memory इस्तेमाल करता है -- यह उन datasets को stream करने के लिए आदर्श है जो RAM में आराम से नहीं समातीं।

उदाहरण: Performance Benefits

python
import sys
list_version = [x for x in range(1000)]  # builds the entire list upfront
gen_version = (x for x in range(1000))  # produces values lazily, one at a time
print(sys.getsizeof(list_version) > sys.getsizeof(gen_version))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.