Labs ICT
๐ŸŽ“ SIWES/IT Login

Generators

1 min read | Python Tutorial
๐ŸŽ“

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

Generator Functions

A generator function uses yield instead of return. It produces a sequence of values lazily, pausing between each yield. State is preserved between calls.

def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

for num in count_up_to(5):
    print(num)

Generator Expressions

Generator expressions look like list comprehensions but use parentheses. They produce items one at a time without storing the whole list in memory.

squares = (x * x for x in range(10))
for s in squares:
    print(s)

๐Ÿงช Quick Quiz

What keyword makes a function a generator?