Iterator & Generator in Python
Iterator
The iterator in python is slightly different from its counterpart in C++. Once a class define __iter__(self) member function and __next__(self) member function, we can use iter() to get its iterator and next() to get the next element of this iterator:
1 | class Number(): |
StopIteration is the end of iterator for every iterator. It is an exception and for can catch and solve it. Therefore, we can also use for to traverse a iterator:
1 | a = [1, 2, 3] |
list,tuple,stringhave implemented iterators.
Generator
The generator is a special type of iterator, which makes a function iterable. Once a function uses yield to return object, this function is a generator:
1 | def func(n): |
When a function becomes a generator, it will not run immediately when called, instead, it will return a generator. When we use next() to traverse the generator, the function will run to the place where yield is, record the address and return a value. Next time, it will run starting from yield. Similarly, it will return StopIteration when finish the function. Therefore, we can also use for to traverse a generator:
1 | for i in func(10): |