Help understanding nested list comprehensions

i’m trying to wrap my head around this code that flattens the dict values lists into one list:

d = { 'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}
result = [item for sublist in d.values() for item in sublist]

result: [1, 2, 3, 4, 5, 6, 7, 8, 9]

i’m a little confused as to what is evaluated first and how this works.
I start by looking at ‘item for sublist in d.values()’, so for each “sublist” in the values of the dict, we look for item in sublist. but where does sublist comes from?
well, from the right hand side ‘for item in sublist’, but its confusing to me, as to what is evaluated first.
so any explanation here about how this works would be appreciated.
thank you very much.

d = { 'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}

result = []

# each of the values in d is a list
for sublist in d.values():
  # iterate through each sublist
  for item in sublist:


So you’re putting each item into a list. you get at each item by going through each sublist in d, and for each sublist, each item in that sublist (sorry, can’t guarantee that syntax is exactly correct, been a while since I wrote any Python)

1 Like

The syntax is perfect, and putting it in a “traditional” nested loop made it crystal clear. thank you for the quick response.