Sobes.tech
Junior — Middle

What unique features does the built-in generator in Python have?

sobes.tech AI

Answer from AI

The built-in generator in Python has the following unique features:

  • Lazy evaluation: generators produce items one at a time as needed, saving memory when working with large data.
  • Use of the yield keyword: allows pausing the function execution and returning a value while preserving the state between calls.
  • Support for iteration: generators are iterators and can be used in for loops and other contexts where iteration is required.

Example of a generator that returns the squares of numbers from 0 to n-1:

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

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

This code outputs: 0, 1, 4, 9, 16 one value at a time.