1

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?

Isiah
  • 195
  • 2
  • 15
  • 1
    they're called "list comprehensions" – Barmar Apr 28 '21 at 22:28
  • https://spapas.github.io/2016/04/27/python-nested-list-comprehensions/ – Barmar Apr 28 '21 at 22:29
  • The order of multiple for-loops in the list comprehension has to match the order of the ordinary for loops. If you keep that in mind, you can deduce the correct order of the for-loops. – Alex G Apr 28 '21 at 22:35

1 Answers1

5
result = [item for row in prices for item in row]
print(result)
Nicholas Hunter
  • 1,791
  • 1
  • 11
  • 14