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])]
print(out)

Prints:

[
    "January_2021",
    "February_2021",
    "March_2021",
    "April_2021",
    "May_2021",
    "June_2021",
    "July_2021",
    "August_2021",
    "September_2021",
    "October_2021",
    "November_2021",
    "December_2021",
    "January_2022",
    "February_2022",
    "March_2022",
    "April_2022",
    "May_2022",
    "June_2022",
    "July_2022",
    "August_2022",
    "September_2022",
    "October_2022",
    "November_2022",
    "December_2022",
]

Leave a Reply