Condense multiple for loops into list comprehension

63 Views Asked by At

How would I do the following in a list comprehension?

asins = []
for item in data['message']['body']['titles']:
    for format in item['formats']:
        for offer in format['offers']:
            asins.append(offer['asin'])
1

There are 1 best solutions below

0
On BEST ANSWER

Just move the append()-contained expression to the front, remove the colons and add brackets around the whole expression:

asins = [offer['asin']
    for item in data['message']['body']['titles']
        for format in item['formats']
            for offer in format['offers']]

The order of for statements otherwise doesn't change. We can now change the indentation and perhaps join the lines if you so wish:

asins = [offer['asin']
         for item in data['message']['body']['titles']
         for format in item['formats']
         for offer in format['offers']]