How to flat multi level list in Python

Simple note how to transform list [1,2,[18,45,87,[7,6]]] to [1,2,18,45,87,7,6].

Variant 1 (python2 and python3)

import collections

def flat(lst):
    result = []
    for i in lst:
        if isinstance(i, collections.Iterable):
            result.extend(flat(i))
        else:
            result.append(i)
    return result

l = [1,2,[18,45,87,[7,6]]]
print(flat(l))    

Variant 2 (python3.3 and above)

def flat(lst):
    if isinstance(lst, list):
        for item in lst:
            yield from flat(item)
    else:        
        yield lst

l = [1,2,[18,45,87,[7,6]]]
print(list(flat(l)))
comments powered by Disqus