Search code examples
pythoncoding-stylecomputer-science

How to expand list comprehension in Python?


I understand that in a normal format of list comprehension like [i for j in k for i in j] This basically can be expanded as:

empty_list = []    
for j in k:
    for i in j:
        empty_list.append(i)

However, I got one question in a recursive function like flatten a nested list with recursive:

def flatten(l:List):
    if isinstance(l, list):
        return [i for j in l for i in flatten(j)]
    else: return [l]

If I just expand this list comprehension, flatten(j) will be in NoneType:

for j in l:
    for i in flatten(j):
        empty_list.append(i)

This will run out as 'NoneType' object is not iterable.

How to expand [i for j in l for i in flatten(j)] in a proper way? Thanks.


Solution

  • This is because in your second example you didn't return a list, you appended to a global. For that to work you would want the following:

    def flatten(l):
        if isinstance(l, list):
            empty_list = []
            for j in l:
                for i in flatten(j):
                    empty_list.append(i)
            return empty_list
        else:
            return [l]
    

    Realistically, I wouldn't use either approach. You're creating a bunch of throw away containers which is expensive. Instead I would use a generator approach:

    def flatten(l):
        if isinstance(l, list):
            for j in l:
                yield from flatten(j)
        else:
            yield l
    
    data = [1, [2, [3]]]
    print(list(flatten(data)))
    
    [1, 2, 3]