python iterator example
Example 1: python defining the iterator protocol
class RangeTen:
def __init__(self, *args): pass
def __iter__(self):
'''Initialize the iterator.'''
self.count = -1
return self
def __next__(self):
'''Called for each iteration. Raise StopIteration when done.'''
if self.count < 9:
self.count += 1
return self.count
raise StopIteration
for x in RangeTen():
print(x)
Example 2: python how to use iter
s = 'hello'
s_iter = iter(s)
print(next(s_iter))
print(next(s_iter))
print(next(s_iter))
print(next(s_iter))
print(next(s_iter))
Example 3: what is iterator in python
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
nums=[2,3,4,5,6,7]
it=iter(nums)
print(it.__next__())
for i in it:
print(i)