Daniel Lemire's blog

, 1 min read

Flattening lists in Python

Can anyone do better than this ugly hack?

def flatten(x):
flat = True
ans = []
for i in x:
if ( i.class is list):
ans = flatten(i)
else:
ans.append(i)
return ans

Update. I like this solution proposed by one of the commenters (sweavo):

def flatten(l):
if isinstance(l,list):
return sum(map(flatten,l))
else:
return l

Can anyone do better?

See also my posts YouTube scalability, Yield returns are not esoteric anymore, Efficient FIFO/Queue data structure in Python and Autocompletion in the Python console.