Created
December 27, 2020 11:17
Iterable, iterator and generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ten_integers(start_from=0): | |
for current in range(start_from, start_from + 10): | |
yield current | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for a in ten_integers(): | |
print(a) | |
manual_iterator = ten_integers(100) | |
for _ in range(0, 10): | |
print(manual_iterator.__next__()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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