Itertools - batched()
making tuples from flat lists
This is a post about itertools functions. You can see all of them Here
You have a flat iterable and need to execute a function getting N items per cycle? This is the function you need.
One situation that happens often in systems integrations is to receive a list of mixed items, that you have to ingest and process is a different way. For example, let's say you receive a list of users, and their ages. The first element in the list is the first name, the second item, is the age for the first user, the third item is the name for the second user, etc...,
Sure you can build a query like tuple(islice(my_list,2)) and put it in a while loop. But there is an easier way: batched. With this function, you can get the N number of items at once, and since this is a generator, you can use it as a regular iterable:
# fcrozetta.dev
from itertools import batched
my_list = [ "alice", 21, "bob", 22, "charlie", 23]
for (name,age) in batched(my_list,2):
print(f"{name} is {age} years old")Simple, and clean.


