Tuesday, June 14, 2011

How to Flatten a List In Python

Here is a simple algorithm to flatten a list in Python. The algorithm also works with the list that have nested lists.

def flatten1(l, newlist):
    if isinstance(l, list):
        for i in l: flatten1(i, newlist)
    else: newlist.append(l)

def flatten2(l):
    if isinstance(l, list):
        newlist = []
        for i in l: newlist = newlist + flatten2(i)
        return newlist
    else: return [l]
    
def flatten3(l):
    if not l: return l
    if not isinstance(l, list): return [l]
    return flatten3(l[0]) + flatten3(l[1:])
    
if __name__ == '__main__':
    l = [1, [2, 3], 4, [[5]], [], [[]], [6, 7, [8]]]
    newlist = []
    flatten1(l, newlist)
    print newlist
    
    print flatten2(l)
    
    print flatten3(l)

The output:
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

The first algorithm is a ugly since it requires a newlist parameter to be passed in. The second one is a bit better but it still requires a loop. The third one doesn't require any loop and is the shortest one.

No comments:

Post a Comment