Skip to content

Instantly share code, notes, and snippets.

@shoeffner
Forked from ahoereth/flatten.py
Created July 3, 2017 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoeffner/0a1e6e4dad405eebc0e828d845398126 to your computer and use it in GitHub Desktop.
Save shoeffner/0a1e6e4dad405eebc0e828d845398126 to your computer and use it in GitHub Desktop.
Python flatten
def flatten(x, depth=-1):
"""Flattens a list of lists into a single list."""
if depth == 0:
return x
if isinstance(x, list):
result = []
for el in x:
if hasattr(el, '__iter__') and not isinstance(el, str):
result.extend(flatten(el, depth - 1))
else:
result.append(el)
return result
elif isinstance(x, tuple):
result = ()
for el in x:
if hasattr(el, '__iter__') and not isinstance(el, str):
sub = flatten(el, depth - 1) if depth < 0 or depth > 0 else el
result += sub
else:
result += (el,)
return result
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment