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

Replace Nested for loop in list-comprehension

I want to combine my id list with my status list and I used list comprehension to do it:

# id
id_list = [
    1, # UAE1S
    2, # UAE2S
    3, # UAE3S
]

# status
status_list = [
    'okay',
    'not okay',
    'unknown',
]

result = [
    {
        'id':id, 
        'status':status,
    }
    
    for id in id_list
        for status in status_list
]

print(result)

[{'id': 1, 'status': 'okay'}, {'id': 1, 'status': 'not okay'}, {'id': 1, 'status': 'unknown'}, {'id': 2, 'status': 'okay'}, {'id': 2, 'status': 'not okay'}, {'id': 2, 'status': 'unknown'}, {'id': 3, 'status': 'okay'}, {'id': 3, 'status': 'not okay'}, {'id': 3, 'status': 'unknown'}]

It’s outputting the correct list but is there a way to remove the nested for loop?

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 :

itertools.product gives the cartesian product,

import itertools
id_list = [1, 2, 3]
status_list = ['okay','not okay','unknown',]
[{'id': item[0], 'status': item[1]} for item in itertools.product(id_list, status_list)]

[{‘status’: ‘okay’, ‘id’: 1}, {‘status’: ‘not okay’, ‘id’: 1}, {‘status’: ‘unknown’, ‘id’: 1}, {‘status’: ‘okay’, ‘id’: 2}, {‘status’: ‘not okay’, ‘id’: 2}, {‘status’: ‘unknown’, ‘id’: 2}, {‘status’: ‘okay’, ‘id’: 3}, {‘status’: ‘not okay’, ‘id’: 3}, {‘status’: ‘unknown’, ‘id’: 3}]

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