Iterator는 lazy evaluation 방식이 적용되기 때문에 메모리 소모가 적다. (iterable variable 값을 통째로 메모리에 올리지 않는다.)
class myIter:
def __init__(self, final_n, multiplier):
self.final_n = final_n
self.multiplier = multiplier
def __iter__(self):
self.curr_n = 0
return self
def __next__(self):
if self.curr_n <= final_n:
multiple = self.curr_n
self.curr_n += self.multiplier
return multiple
else:
raise StopIteration
my_iter_init = myIter(20000000000000000000000, 5)
my_iter_obj = iter(my_iter_init)
next(my_iter_obj) # 0
next(my_iter_obj) # 5
next(my_iter_obj) # 10
next(my_iter_obj) # 15
next(my_iter_obj) # 20 ....
x = [x * 5 for x in range(2000000000000000000000)] # memory error
하나의 value를 한번씩 내뱉도록 하는 함수 (iterator와 비슷하지만 yield를 사용하는 것이 다름.)
Iterator와 같이 한번에 메모리에 올리지 않는다.
def my_gen():
x = 5
y = 7
print("a")
yield x, y
x += 1
y += 2
print("b")
yield x, y
x += 3
y += 4
print("c")
yield x, y
my_gen()
# a
# 5, 7
my_gen()
# b
# 6, 9
my_gen()
# c
# 9, 13