Sobes.tech
Middle

What is the difference between a decorator and a generator? When is it better to use a generator instead of a list?

sobes.tech AI

Answer from AI

A decorator is a function that takes another function and returns a new function with extended behavior, without modifying the original code.

A generator is a function that returns an iterator and allows values to be produced step-by-step using the yield keyword.

When to use a generator instead of a list:

  • If you need to process large amounts of data without loading the entire collection into memory.
  • When lazy evaluation is important — values are generated as needed.

Example of a generator:

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

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

Decorator example:

def decorator(func):
    def wrapper():
        print("Before calling the function")
        func()
        print("After calling the function")
    return wrapper

@decorator
def say_hello():
    print("Hello")

say_hello()