Created
April 1, 2015 20:47
-
-
Save saxbophone/f71dd97f68492d5c3b28 to your computer and use it in GitHub Desktop.
Python Flatten Nested Lists
This file contains 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_list(l, ignore_iterables=True): | |
""" | |
Flatten out nested lists and return a non-nested list. | |
By default, ignores other iterables. | |
""" | |
if ignore_iterables: | |
arr = [] | |
if isinstance(l, list): | |
for item in l: | |
if isinstance(item, list): | |
subs = flatten_list(item, | |
ignore_iterables=ignore_iterables) | |
for sub_item in subs: | |
arr.append(sub_item) | |
else: | |
arr.append(item) | |
return arr | |
else: | |
return [l] | |
else: | |
arr = [] | |
if hasattr(l, '__iter__'): | |
for item in l: | |
if hasattr(item, '__iter__'): | |
subs = flatten_list(item, | |
ignore_iterables=ignore_iterables) | |
for sub_item in subs: | |
arr.append(sub_item) | |
else: | |
arr.append(item) | |
return arr | |
else: | |
return [l] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment