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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post