Replace Nested for loop in list-comprehension

Question:

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?

Asked By: Prosy Arceno

||

Answers:

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}]

Answered By: Jisson
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.