Skip to content

Instantly share code, notes, and snippets.

@antomor
Created December 27, 2020 11:17
Iterable, iterator and generator
for a in TenIntegers():
print(a)
manual_iterator = TenIntegers(100)
for _ in range(0, 10):
print(manual_iterator.next())
# iterating 11 times, it raises an error
for _ in range(0, 11):
print(manual_iterator.next())
def ten_integers(start_from=0):
for current in range(start_from, start_from + 10):
yield current
for a in ten_integers():
print(a)
manual_iterator = ten_integers(100)
for _ in range(0, 10):
print(manual_iterator.__next__())
class TenIntegers:
def __init__(self, start_from=0):
self.current=start_from
self.max = self.current + 10
def __iter__(self):
'''
This method makes the object iterable
'''
return self
def __next__(self):
'''
This is the actual method used on iteration
'''
if self.current < self.max:
current_value = self.current
self.current += 1
return current_value
else:
# This error is raised to stop the iteration
raise StopIteration
# Useful to call it manually
next = __next__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment