DEV Community

sumandari
sumandari

Posted on • Edited on

Random todos with iterator vs generator

we can iterate objects in a list:

>>> persons = ["you", "I", "they"]
>>> for person in persons:
...     print(person)
... 
you
I
they
>>> 

Enter fullscreen mode Exit fullscreen mode

We can also create an iterable object that will behave like a list with __iter__ magic method. And put logic on __next__ method.

>>> import requests
>>> class RandomTodos:
...     url: str = 'https://jsonplaceholder.typicode.com/todos/'
...     def __init__(self, start=1):
...         self.current = start
...     def __next__(self):
...         current = self.current
...         res = requests.get(f"{self.url}{current}")
...         self.current += 1
...         return res.json().get('title', 'nothing todo')
...     def __iter__(self):
...         return self
... 
>>> person = ["you", "I", "they"]
>>> from pprint import pprint 
>>> pprint(list(zip(person, RandomTodos())))
[('you', 'delectus aut autem'),
 ('I', 'quis ut nam facilis et officia qui'),
 ('they', 'fugiat veniam minus')]
>>> todo = RandomTodos(3)
>>> next(todo)
'fugiat veniam minus'
>>> next(todo)
'et porro tempora'
Enter fullscreen mode Exit fullscreen mode

We can also use generator for that

>>> def random_todos(start=1):
...     url = "https://jsonplaceholder.typicode.com/todos/"
...     while True:
...         res = requests.get(f"{url}{start}")
...         yield res.json().get('title', 'nothing todo')
...         start += 1
... 
>>> todos = random_todos()
>>> next(todos)
'delectus aut autem'
>>> next(todos)
'quis ut nam facilis et officia qui'
>>> next(todos)
'fugiat veniam minus'
>>> person = ["you", "I", "they"]
>>> from pprint import pprint
>>> pprint(list(zip(person, random_todos())))
[('you', 'delectus aut autem'),
 ('I', 'quis ut nam facilis et officia qui'),
 ('they', 'fugiat veniam minus')]

Enter fullscreen mode Exit fullscreen mode

read more about iterator: https://wiki.python.org/moin/Iterator

free api endpoints for testing: https://jsonplaceholder.typicode.com

Top comments (0)