Skip to content

Instantly share code, notes, and snippets.

@ivanleoncz
Last active June 14, 2021 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanleoncz/2506480daf6e4b78fca25ca7a0af8e08 to your computer and use it in GitHub Desktop.
Save ivanleoncz/2506480daf6e4b78fca25ca7a0af8e08 to your computer and use it in GitHub Desktop.
Custom iterator object examples.
class MyIterator:
def __init__(self, limit):
self.limit = limit
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= self.limit:
x = self.a
self.a += 1
return x
else:
raise StopIteration
obj = MyIterator(10)
my_iter = iter(obj)
for x in my_iter:
print(f"Step: {x}")
class MyIterator:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
obj = MyIterator()
my_iter = iter(obj)
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
class MyIterator:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
obj = MyIterator()
my_iter = iter(obj)
for i in my_iter:
print(i)
if i == 10:
print("This iteration will go forever if we don't stop it...")
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment