Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list of lists / nested lists to list of lists without nesting

I want to convert my list of lists and within these lists there are list into only list of lists. For example:

My code:

a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
aaa = len(a)
aa = [[] for i in range(aaa)]
for i, x in enumerate(a):
    if len(x) != 0:
        for xx in x:
            for xxx in xx:
                aa[i].append(xxx)
print(aa)

Currently:

a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]

to expected:

[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]

My current code works in finding the expected output. However, i have to use too many for loop and its too deep. Is there a shorter way to do so like just in one or 2 lines?

like image 289
Beginner Avatar asked Dec 21 '25 03:12

Beginner


1 Answers

You can do it with list comprehension, just by checking to see whether the nested list is empty or not, and, if not, replacing the outer list with the inner list (by index).

data = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]

result = [d[0] if d else d for d in data]
print(result)

# OUTPUT
# [[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
like image 122
benvc Avatar answered Dec 22 '25 18:12

benvc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!