How to make a nested list comprehension?

Question:

I have a 2D list:

prices = [[0.11, 0.25, 0.37],
          [0.40, 0.72, 0.21],
          [0.03, 0.56, 0.23], ]

and I want to empty the contents of each of the items in each row into one list. I can easily do this with a nested for loop as such:

for row in prices:
    for item in row:
        result.append(item)
print(result)

However I want to do this in a inline for loop. At first I tried this:

print([[item for item in row] for row in prices])

However that just returns the exact same list (prices). I’ve also tried this:

print([[[x for x in item] for item in row] for row in prices])

but that returns an error because it tries to iterate over the floats inside the lists. Is there a way to do this?

Asked By: Haisi

||

Answers:

result = [item for row in prices for item in row]
print(result)
Answered By: Nicholas Hunter
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.