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 ;)
for elem in lst:
if type(elem) in (tuple, list):
for i in flatten(elem):
# example usage
>>> nested = [('a', 'b', ['c', 'd'], ['a', 'b']), ['e', 'f']]
0 # woops!
>>> flattened = list( flatten(nested) )
['a', 'b', 'c', 'd', 'a', 'b', 'e', 'f']
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
Isn't it about time forums rewarded their contributors?
Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.
It's as simple as contributing editorial or replying to discussions labeled
OP Sponsor or
This is an OP Kudos discussion and contributors
may be rewarded