Sobes.tech
Junior — Middle

Explain the working principle of generators in Python and their main advantages

sobes.tech AI

Answer from AI

Generators in Python are special functions that return an iterator and allow values to be produced one at a time, while maintaining their state between calls.

Main working principle:

  • Instead of a regular return, yield is used, which returns a value and pauses the function.
  • On the next call, execution continues from after the yield.

Advantages of generators:

  • Memory efficiency — no need to store the entire dataset in memory, values are generated on demand.
  • Convenience when working with large or infinite sequences.
  • Clean and understandable code for iteration.

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)

This code will output numbers from 1 to 5, generating them one by one.

Explain the working principle of generators in Python… - sobes.tech