Labs ICT
โญ Pro Login

Generators

1 min read | Python Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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?