-1

I was working on flattening this multidimensional list

f_list =[[[1, 2, 3]], [[4, 5, 6]], 
[[7, 8, 9]]]

and i did using nested for loops like so

new_l=[]
for sublist in f_list:
    for subsublist in sublist:
        for i in subsublist:
            new_l.append(i)
print(new_l)

but i want to convert it using list comprehension but i am confused on how to go about it. i've read some documentation where it said to take the last bit of the loop to start off and go from top to bottom but, it did not work

new_l =[i for subsublist in f_list for sublist in subsublist for  sublist in f_list]

and tried this as well

new_l =[i for subsublist in sublist for subsublist in sublist for  sublist in f_list]

i am very confused

devuser
  • 7
  • 4
  • Does this answer your question? [List comprehension on a nested list?](https://stackoverflow.com/questions/18072759/list-comprehension-on-a-nested-list) – funnydman Jul 28 '22 at 13:11

3 Answers3

1

Let's go one step at a time:

Step 1:

new_l=[]
for sublist in f_list:
    for subsublist in sublist:
        [new_l.append(i) for i in subsublist]

Step 2:

new_l=[]
for sublist in f_list:
    [new_l.append(i) for subsublist in sublist for i in subsublist]

Step 3:

new_l = []
[new_l.append(i) for sublist in f_list for subsublist in sublist for i in subsublist]

And finally:

new_l = [i for sublist in f_list for subsublist in sublist for i in subsublist]

You might want to take a look at Flattening an irregular list of lists

The Thonnu
  • 3,578
  • 2
  • 8
  • 30
0

The approach is to go from top to bottom while converting nested loops to list comprehension.

f_list =[[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]]

new_l = [i for sublist in f_list for subsublist in sublist for i in subsublist]

print(new_l)
Msvstl
  • 1,116
  • 5
  • 21
-1

Here is your solution:

[i for sublist in f_list for subsublist in sublist   for i in subsublist ]
iaggo
  • 51
  • 5