Skip to content

Instantly share code, notes, and snippets.

@stephengruppetta
Created July 13, 2023 12:17
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 stephengruppetta/2941d1e9870cac21e6e37f53bcc5ab61 to your computer and use it in GitHub Desktop.
Save stephengruppetta/2941d1e9870cac21e6e37f53bcc5ab61 to your computer and use it in GitHub Desktop.
class MyList:
def __init__(self, iterable):
self.items = iterable
def __iter__(self):
print(f"Calling __iter__ in MyList")
return MyListIterator(self.items)
class MyListIterator:
def __init__(self, iterable):
self.items = iterable
self.index = 0
def __iter__(self):
print("Only called when iterating over iterator itself")
return self
def __next__(self):
if self.index < len(self.items):
item = self.items[self.index]
self.index += 1
return item
else:
raise StopIteration
numbers = MyList([2, 5, 10, 3, 99, 42])
# Unpacking numbers
print(*numbers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment