Overview

iterable은 반복 가능한 객체인 반면, iterator는 반복을 수행하는 객체이다. 새로운 데이터 타입을 만들 때, 그 데이터 타입이 반복 가능한 성질을 갖도록 할 때 이터레이터를 사용한다.

Iterator

Iterator(이터레이터)는 순서대로 하나씩 값을 리턴할 수 있는 객체이다.

nums = [10, 20, 30]
it = iter(nums)

print(next(it))
print(next(it))
print(next(it))
print(next(it))  # E
nums = [10, 20, 30]
it = iter(nums)

print(it.__next__())
print(it.__next__())
print(it.__next__())
print(it.__next__())  # E

[Option] Class로 직접 구현

class MyIterator:
    def __init__(self, x):
        self.x = x
        self.position = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.position >= len(self.x):
            raise StopIteration
        result = self.x[self.position]
        self.position += 1
        return result

i = MyIterator(["apple", "banana", "cherry"])
for item in i:
    print(item)
class MyIterator:
    def __init__(self, x):
        self.x = x
        self.position = len(self.x) -1

    def __iter__(self):
        return self

    def __next__(self):
        if self.position < 0:
            raise StopIteration
        result = self.x[self.position]
        self.position -= 1
        return result

i = MyIterator(["apple", "banana", "cherry"])
for item in i:
    print(item)