1

I have a nested for loop but I can't for the life of me figure out how to transform it to a nested list comprehension. I don't seem to understand how nested list comps work, so if you could add explanation as well that would be extremely helpful.

Here is the data structure from which I'm trying to extract with the loop (It's for a marketing API):

list_of_orders = [{'Campaign ID': 1234, 'Orders': [{'Order ID': 0001, ...}, {'Order ID': 0002, ...}, ...]}, {'Campaign ID': 5678, 'Orders': [{...}, ...]}, ...]

Here is the loop:

order_ids = []
for i in list_of_orders:
    for order in i.get('Orders'):
        order_ids.append(str(order.get('Order ID')))

How could I - and should I - transform this into a list comp? Is that faster / more pythonic / a better practice?

bende
  • 83
  • 2
  • 10
  • 1
    Why is this considered a duplicate? It's about a nested list comprehension, not list comprehensions in general. – Praind Jan 24 '19 at 10:46

2 Answers2

3

The following should work:

order_ids = [str(order.get('Order ID')) for i in list_of_orders for order in i.get('Orders')]

The order of the nested for expressions is counter-intuitive to some people as it does not really correspond to natural language scoping.

It might be minutely faster than the loop based approach, but it is has the same asymptotic time complexity. And while comprehensions are Pythonic, the Zen of Python states: "Readability counts"! So I'd stick with the loops.

schwobaseggl
  • 55,463
  • 4
  • 39
  • 63
  • Thank you so much, this is super helpful! I think with this example I also got what I don't understand about the nested list comps (normal list comps are fine, I am loving them and using them a lot!). So If I understand correctly, what you want to retrieve should be the first (order.get('Order ID'), and then you go level by level for i... for order... --> if I think of a for loop and put the thing I want to append as first, then follow the loop, I should get the list comp structure. Is that correct? – bende Jan 24 '19 at 10:58
0

How could I - and should I - transform this into a list comp? Is that faster / more pythonic / a better practice?

Yes. No. No.

Dan D.
  • 67,516
  • 13
  • 93
  • 109