Generator
Generator
A function that produces values one at a time with yield. Memory-efficient iteration. Supported in Python and JavaScript.
Generator
A function that produces values one at a time with yield. Memory-efficient iteration. Supported in Python and JavaScript.
A Generator is a special function that uses the yield keyword to produce values one at a time. Unlike a regular function, it does not return all results at once; it produces the next value each time it is called. This makes it possible to process sequences in a memory-efficient way and even to represent infinite sequences.
The core of a generator is that it preserves its execution state. The function pauses at yield, and when next() is called, it resumes from that point. All state, including the function's local variables and execution position, is preserved. This is the mechanism that underlies coroutines.
In Python, a generator can be created in two ways. You can define a function that contains yield, or use a generator expression (x*2 for x in range(10)). Both approaches automatically implement the iterator protocol, so they can be used directly in a for loop.
In JavaScript, generators are defined with the function* syntax. async/await actually began as syntactic sugar over generators, and libraries such as Redux-Saga use generators to implement asynchronous flow control. In Rust, the Iterator trait and async/await provide similar concepts.
# Python 제네레이터 예제
# 기본 제네레이터 함수
def countdown(n):
while n > 0:
yield n
n -= 1
print("발사!")
for num in countdown(5):
print(num) # 5, 4, 3, 2, 1, "발사!"
# 무한 시퀀스 제네레이터
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
print([next(fib) for _ in range(10)]) # [0,1,1,2,3,5,8,13,21,34]
# 제네레이터 표현식
squares = (x**2 for x in range(10))
print(list(squares)) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 파일 처리 (메모리 효율적)
def read_large_file(file_path):
with open(file_path) as f:
for line in f:
yield line.strip()
# send()로 양방향 통신
def accumulator():
total = 0
while True:
value = yield total
if value is not None:
total += value
acc = accumulator()
next(acc) # 시작
print(acc.send(10)) # 10
print(acc.send(20)) # 30
Data Engineer: "I'm fetching 1 million rows from the DB to process them, but I'm running out of memory."
Senior Developer: "Instead of fetching everything at once, how about processing it in chunks with a generator?"
Data Engineer: "So I can wrap the cursor in a generator and yield from it."
Senior Developer: "Right. If you set the batch size to around 1000 and yield each batch, memory usage stays constant."
Interviewer: "What is the difference between a generator and a list comprehension?"
Candidate: "A list comprehension creates all elements immediately and stores them in memory, whereas a generator expression produces values only on request. For large datasets, generators are far more memory-efficient."
Interviewer: "What is yield from used for?"
Candidate: "It is used to delegate to the values of another generator. Instead of nested loops, you can express it concisely with yield from sub_generator()."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: "This function appends to a list and returns it at the end; I think it would be better to change it to a generator."
Author: "Can I just use yield instead of return?"
Reviewer: "Yes, yield instead of append, and remove the return statement. Then it is processed in a streaming fashion without an intermediate list."
Author: "Are there any downsides?"
Reviewer: "That it can be iterated over only once. If you need to iterate multiple times, you have to convert it with list() or call the function again."