Skip to content

Instantly share code, notes, and snippets.

@lssergey
Created November 8, 2012 20:44
Show Gist options
  • Save lssergey/4041457 to your computer and use it in GitHub Desktop.
Save lssergey/4041457 to your computer and use it in GitHub Desktop.
List flattening
# Python does not have tail recursion optimization,
# so this function can't handle too deep data structures.
# This piece of code was written as a practicing task.
def flatten(l):
nested = None
for i, e in enumerate(l):
if isinstance(e, list):
nested = e; break
if nested is not None:
return flatten(l[:i] + nested + l[i+1:])
else: return l
def flatten2(l):
if not isinstance(l, list): return [l]
if not l: return l
return flatten(l[0]) + flatten(l[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment