Skip to content

Instantly share code, notes, and snippets.

@ahoereth
Created July 3, 2017 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahoereth/de4e88bc60fc1e2f075f5bbec827b016 to your computer and use it in GitHub Desktop.
Save ahoereth/de4e88bc60fc1e2f075f5bbec827b016 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
@Berkcem
Copy link

Berkcem commented Nov 29, 2019

Hello ahoereth. Am I allowed to use part of this code for commercial use?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment