Generators, Iteratos - AndrewMZ6/python_cheat_sheet GitHub Wiki
First of all - every generator is iterator while not every iterator is generator!
Second of all - iterators and iterable objects are not the same. Iterable objects are objects that can be
converted into iterators. For this to hapen they must have __iter__
method to be defined, and when it gets
called iterables turn into iterators.
Iterators have __iter__
method defined also but when called it returns the iterator itself. The main difference
is that iterators have __next__
method defined and when called it returns current value of sequence, changes the current value
so next time the __next__
method gets called iterator returns new value.
Generators return value with yield
instruction
For example let's consider a list
L = [1, 2, 3]
If we try to pass it to next()
inbuilt function
next(L)
we get error that says that list L
is not an iterator!
Traceback (most recent call last):
File "E:\Code\Python\test19.py", line 3, in <module>
next(L)
TypeError: 'list' object is not an iterator
now let's check what names are defined in list
's scope
print(L.__dir__())
output
['some other names', ..., '__iter__', ... ,'some other names']
We can see that there's __iter__
method so let's use iter()
function
iter_L = iter(L)
and try to call the next
element
next(iter_L)
next(iter_L)
next(iter_L)
next(iter_L)
output
1
2
3
Traceback (most recent call last):
File "E:\Code\Python\test19.py", line 9, in <module>
print(next(iter_L))
StopIteration