Sobes.tech
Junior — Middle

How can a data or object generation mechanism be implemented?

sobes.tech AI

Answer from AI

In Python, the mechanism for generating data or objects is often implemented using generators — functions with the keyword yield. They allow creating sequences of values one at a time without storing the entire sequence in memory.

You can also use generator expressions, which are similar to list comprehensions but return a generator.

Example of a generator function:

def generate_squares(n):
    for i in range(n):
        yield i * i

for square in generate_squares(5):
    print(square)

Example of a generator expression:

squares = (x * x for x in range(5))
for square in squares:
    print(square)

This approach saves memory and allows working with potentially infinite sequences.