1,105,625 Community Members

flatten nested lists

Member Avatar
Reputation Points: 6 [?]
Q&As Helped to Solve: 73 [?]
Skill Endorsements: 1 [?]
 
1
 

The name says it all, I think. You have a nested list, you want to flatten it (e.g. because you want to count the occurence of an element), this function is all you need ;)

def flatten(lst):
    for elem in lst:
        if type(elem) in (tuple, list):
            for i in flatten(elem):
                yield i
        else:
            yield elem

# example usage
>>> nested = [('a', 'b', ['c', 'd'], ['a', 'b']), ['e', 'f']]
>>> nested.count("a")
 0   # woops!
>>> flattened = list( flatten(nested) )
>>> flattened
 ['a', 'b', 'c', 'd', 'a', 'b', 'e', 'f']

>>> flattened.count("a")
 2   # that's better

# with flatten() you can do everything you can do with generators,
# like such boring things
>>> for elem in flatten(nested):
....          print elem     
....
a
b
c
d
a
b
e
f
You
Post:
Start New Discussion
Tags Related to this Article