Iterator
Iterator
An object that traverses the elements of a collection. Implemented in Python with __iter__ and __next__. The basis of the for loop.
Iterator
An object that traverses the elements of a collection. Implemented in Python with __iter__ and __next__. The basis of the for loop.
An iterator is both a design pattern and an object for sequentially accessing the elements of a collection. It makes it possible to traverse the elements one by one without exposing the collection's internal structure. It is a core concept that underlies the for loop in most modern programming languages.
In Python, an iterator is an object that implements the __iter__() and __next__() methods. __iter__() returns the iterator itself, and __next__() returns the next element or raises a StopIteration exception. All iterable objects, such as lists, dictionaries, and strings, provide an iterator.
The key advantage of iterators is lazy evaluation. Rather than loading all elements into memory in advance, they generate them one at a time, as needed. This makes it possible to handle infinite sequences, and greatly improves memory efficiency when processing large amounts of data.
In JavaScript, the iterator protocol is followed by implementing Symbol.iterator. The for...of loop, the spread operator (...), and destructuring assignment all make use of iterators. In Rust, the Iterator trait plays this role, and it provides a rich set of adapters such as the functional-style map, filter, and collect.
# Python 이터레이터 예제
# 커스텀 이터레이터 클래스
class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
# 사용 예시
for num in CountDown(5):
print(num) # 5, 4, 3, 2, 1
# 내장 이터레이터 함수들
numbers = [1, 2, 3, 4, 5]
# iter()와 next()
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2
# 이터레이터 도구들
from itertools import islice, cycle, chain
# 처음 3개만 가져오기
first_three = list(islice(numbers, 3)) # [1, 2, 3]
# 무한 반복
infinite = cycle([1, 2, 3])
print([next(infinite) for _ in range(7)]) # [1,2,3,1,2,3,1]
# 여러 이터러블 연결
combined = list(chain([1, 2], [3, 4])) # [1, 2, 3, 4]
Data Engineer: "I'm processing a 10GB log file, and I'm running out of memory, causing an OOM."
Senior Developer: "Don't read the whole file into a list; just process it one line at a time with an iterator."
Data Engineer: "Can I just use the file object itself as an iterator instead of readline()?"
Senior Developer: "Yes, if you write it as for line in file:, it automatically reads one line at a time. Memory usage stays constant."
Interviewer: "What is the difference between an iterable and an iterator?"
Candidate: "An iterable is an object that has an __iter__ method and can return an iterator. Lists and dictionaries are examples. An iterator is an object that has a __next__ method and performs the actual traversal."
Interviewer: "What are the advantages of the iterator pattern?"
Candidate: "It hides the internal structure of a collection and provides a consistent interface. In addition, lazy evaluation gives good memory efficiency, and it can also represent infinite sequences."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: "Here you're loading everything into memory with list(). Could we just use the iterator as it is?"
Author: "I converted it to a list because it has to be traversed multiple times. An iterator can only be used once, right?"
Reviewer: "Right. But if you use itertools.tee, you can duplicate the iterator. Or you could write a generator function and create a new one each time you need it."
Author: "Good suggestion. Since the data is large, I'll apply the factory pattern with a generator function rather than tee."