- An iterable is an object, obj, that produces an iterator via the syntax iter(obj).
- An iterator is an object that manages the iteration of a series of values.
If variable it identifies an iterator object, then each call to the built-in function, next(it), produces a subsequent element from the underlying series, with a StopIteration exception raised to indicate that there are no further elements.
A snapshot iterator ensures that the iterator reports elements that existed at the time the iterator was created, even if the contents of the collection have since changed.
However, most Python iterators use a technique called lazy iteration, with the iterator waiting until each individual value is requested before performing much of the work.
하지만, 큰 데이터를 다룰 때에는 iterator보다 generator가 훨씬 효율성 측면에서 유리합니다.
A generator is implemented with a syntax that is very similar to a function, but instead of returning values, a yield statement is executed to indicate each element of the series.
def factors(n): # traditional function that computes factors
results = [] # store factors in a new list
for k in range(1,n+1):
if n % k == 0: # divides evenly, thus k is a factor
results.append(k) # add k to the list of factors
return results # return the entire list
def factors(n): # generator that computes factors
for k in range(1,n+1):
if n % k == 0: # divides evenly, thus k is a factor
yield k # yield this factor as next result
iterator과는 달리, generator는 최초 iterable한 객체가 존재하지 않아도 됩니다.
무슨 말이냐면, iterator를 생성하기 위해서는 최초 iter(myList) 처럼 list, tuple과 같은 iterable을 활용해야만 합니다.
하지만 generator 같은 경우에는 기존의 값을 저장해 두어야 할 iterable이 요구되지 않으며, 호출 시에 이전 중지된 yield 문 이후에서 이어서 호출되는 방식이기 때문에, 대용량의 데이터를 다룰 때 훨씬 efficient 합니다.
'python' 카테고리의 다른 글
Bitwise Operators (0) | 2025.02.21 |
---|---|
Files and Exceptions (0) | 2025.02.10 |
Tuple 튜플 (0) | 2025.01.26 |
List 리스트 (0) | 2025.01.26 |
Terminating a Program (프로그램 종료) (0) | 2025.01.12 |