Sobes.tech
Junior — Middle

What is the difference between a regular function and a generator in programming?

sobes.tech AI

Answer from AI

A regular function in Python executes the code and returns a result once using the return statement. After that, the function execution ends.

A generator is a function that uses the yield keyword to produce values step-by-step. Instead of returning all values at once, a generator pauses its execution and yields a value, and upon the next call, it continues from where it left off.

Example:

# Regular function
def get_numbers():
    return [1, 2, 3]

# Generator
def generate_numbers():
    yield 1
    yield 2
    yield 3

for num in generate_numbers():
    print(num)

Generators are useful for saving memory when working with large sequences, as values are generated on demand.

What is the difference between a regular function and… - sobes.tech