Sobes.tech
Junior — Middle

What methods of creating generators do you know in Python?

sobes.tech AI

Answer from AI

In Python, generators can be created in two main ways:

  1. Using the yield keyword in a function — a function with yield returns a generator that can be iterated over.
def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1

for number in count_up_to(5):
    print(number)
  1. Generator expressions — similar to list comprehensions, but return a generator instead of a list.
squares = (x*x for x in range(5))
for square in squares:
    print(square)

Both methods allow for lazy generation of sequences, saving memory.