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:
- Using the
yieldkeyword in a function — a function withyieldreturns 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)
- 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.