Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate list from other 2 lists by repeating – looking for a built-in function

Given:

date_range = ['2022-05-27','2022-05-28']
hour_range = [0,2,4,6]

I want to generate:

[
    ('2022-05-27',0),
    ('2022-05-27',2),
    ('2022-05-27',4),
    ('2022-05-27',6),
    ('2022-05-28',0),
    ('2022-05-28',2),
    ('2022-05-28',4),
    ('2022-05-28',6),
]

I tried zip(), map(), etc. which doesnt exactly get the expected output. What built-in function can I use to avoid writing multiple loops?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You want itertools.product():

from itertools import product
list(product(date_range, hour_range))

This outputs:

[
 ('2022-05-27', 0), ('2022-05-27', 2), ('2022-05-27', 4), ('2022-05-27', 6), 
 ('2022-05-28', 0), ('2022-05-28', 2), ('2022-05-28', 4), ('2022-05-28', 6)
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading