Created
July 3, 2017 08:46
-
-
Save ahoereth/de4e88bc60fc1e2f075f5bbec827b016 to your computer and use it in GitHub Desktop.
Python flatten
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Hello ahoereth. Am I allowed to use part of this code for commercial use?