Skip to content

Instantly share code, notes, and snippets.

@saxbophone
Created April 1, 2015 20:47
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 saxbophone/f71dd97f68492d5c3b28 to your computer and use it in GitHub Desktop.
Save saxbophone/f71dd97f68492d5c3b28 to your computer and use it in GitHub Desktop.
Python Flatten Nested Lists
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