Iterator: bất kỳ object nào implement __iter__() và __next__(). Generator: function dùng yield — tự động implement iterator protocol, lazy, stateful.
python
# Class-based Iterator
class CountDown:
def __init__(self, start): self.current = start
def __iter__(self): return self # Trả về chính nó
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
list(CountDown(3)) # [3, 2, 1]
# Generator function — ngắn gọn hơn
def countdown(n):
while n > 0:
yield n
n -= 1
# Generator expression — lazy (khác list comprehension)
gen = (x**2 for x in range(1_000_000)) # Không chiếm RAMGenerator với send() — coroutine-lite, nhận value từ caller:
python
def accumulator():
total = 0
while True:
value = yield total # Nhận value từ .send()
if value is None: break
total += value
acc = accumulator()
next(acc) # Khởi động generator
acc.send(10) # 10
acc.send(20) # 30