python
으로 LinkedList
를 자료구조를 구현해보라고?note
LinkedList
를 언제쯤 구현할 수 있을까?
이제 __iter__()
함수가 보인다.
iterator
와 iterable
의 차이는 또 무엇인고?
아~ 진짜 LinkedList
만들기 어렵다.
왜? Iterable
과 Iterator
를 나누어 놓아서 혼란스럽게 하나?
굳이 구분해야 싶기도 하다.
일단 모르니, 정의 부터!
파이썬 공식문서를 보면 Iterable 과 Iterator 를 아래와 같이 정의한다.
Iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an
__iter__()
method or with a__getitem__()
method that implements sequence semantics.
Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), …). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator.
Iterator
An object representing a stream of data. Repeated calls to the iterator’s
__next__()
method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its__next__()
method just raise StopIteration again. Iterators are required to have an__iter__()
method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.
그래서 저 영어 속에서 차이를 어떻게 찾아내야 하냐고!
Iterator 는 간단히 말해
연속적인 데이터를 저장하고 객체이다. 그리고 반복적인next()
를 사용하여 연속적인 item
에 접근할 수 있어야 한다.
An object representing a stream of data. Repeated calls to the iterator’s
__next__()
method (or passing it to the built-in function next()) return successive items in the stream.
여기서 한번 더 집고 넘어가야 할건!
next()
함수를 명시적으로 사용할 수 있어야 Iterator 이다.
그럼, Iterable 은 무엇일까?
한 번에 하나씩 저장된 값들을 가져올 수 있는 객체다.
An object capable of returning its members one at a time.
아래의 MyCount
클래스는 Iterable
하지만 Iterator
는 아니다.
for
문으로 한 번에 하나씩 저장된 값들을 가져 올 수 있지만,
명시적으로 iter()
와 next()
를 호출 할수 없기 때문이다.
class MyCount:
def __init__(self, stop):
self.start = 1
self.stop = stop
def __iter__(self):
while self.start != self.stop:
yield int(self.start)
self.start = self.start +1
myCount = MyCount(10)
for i in myCount:
print(i)
iterMyCount = iter(myCount)
print(next(iterMyCount))
output
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
File "/workspace/firstContainer/data_structure/Iterable_Test.py", line 15, in <module>
next(myCount)
TypeError: 'MyCount' object is not an iterator
MyCount
같은 클래스를 Generator Types
의 iterator
라고 한다.
자! 이렇게 정리하자!
Iterator
: 명시적으로 next()
와 iter()
를 호출할 수 있는 것Iterable
: 암묵적으로 next()
와 iter()
를 호출할 수 있는 것