Preserve ordering of Python's itertools.product

I want to find all the combinations of two lists using itertools’ product function:

from itertools import product
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
years = ['2021', '2022']
list(product(*[months, years]))

This outputs

 [('January', '2021'), ('January', '2022'), ('February', '2021'), ('February', '2022'), ('March', '2021'), ('March', '2022'), ('April', '2021'),

and so on. Is it possible to preserve the order of the months list? I also want to convert the tuples to strings where the months and years elements are separated by _.

This is what I’m aiming to get:

['January_2021', 'February_2021', 'March_2021', 'April_2021', ...

>Solution :

Just swap the lists in itertools.product:

out = [f"{m}_{y}" for y, m in product(*[years, months])]



Leave a Reply