remove brackets from nested list

Question:

I have a nested list that looks like this

[[[0]],
[[2], [1]],
[[3]],
[[4]],
[[5]],
[[6]],
[[7]],
[[8]],
[[9, 10]],
[[11]],
[[13], [12]]]

I want to simplify it into not flatten everything

[[0], [2], [1],[3],[4],[5],[6],[7],[8],[9,10],[11],[13],[12]]

simplify the nested list.

Asked By: ZAHR

||

Answers:

What you want to do is a variation of "flattening" of the arrays. here’s an example solution for this:

nested_list = [[[0]],
[[2], [1]],
[[3]],
[[4]],
[[5]],
[[6]],
[[7]],
[[8]],
[[9, 10]],
[[11]],
[[13], [12]]]

simplified_list = []
for sub_list in nested_list:
    for item in sub_list:
        simplified_list.extend([item])

print(simplified_list)

it generates the output: [[0], [2], [1], [3], [4], [5], [6], [7], [8], [9, 10], [11], [13], [12]]

Answered By: Unamata Sanatarai

Use (my_list is the original):

flat = [item for sublist in my_list for item in sublist]
print(flat)
Answered By: user19077881
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.