I am reading What exactly are Python's iterator, iterable, and iteration protocols? But why do we need to use "iterators"? As shown below, we can use a simple list
with indexing method:
Using list
s= 'cat'
print s[0]
print s[1]
print s[2]
print s[3]
Output:
C:\Users\test\Desktop>python iterator.py
c
a
t
Traceback (most recent call last):
File "iterator.py", line 9, in <module>
print s[3]
IndexError: string index out of range
C:\Users\test\Desktop>
Using iterator
s = 'cat'
t = iter(s)
print next(t)
print next(t)
print next(t)
print next(t)
Output:
C:\Users\test\Desktop>python iterator.py
c
a
t
Traceback (most recent call last):
File "iterator.py", line 36, in <module>
print next(t)
StopIteration
C:\Users\test\Desktop>