Mastering Python Generators: Efficiently Manage Data with Yield

Rumman Ansari   Software Engineer   2024-07-26 02:26:21   259  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

  • A Generator object is an iterator, whose values are created at the time of accessing them.

  • A generator can be obtained either from a generator expression or a generator function.

Example

x = [6, 3, 1]
g = (i**2 for i in x) # generator expression
print(next(g)) # -> 36

def gen_number():  # generator function
    x = [6, 3, 1]
    for i in x:
        yield i**2
x = gen_number()
next(x)            # -> 36
MCQ Available

There are 4 MCQs available for this topic.

4 MCQ