Skip to content

Instantly share code, notes, and snippets.

@mittenchops
Last active December 19, 2015 16:29
Show Gist options
  • Save mittenchops/5984652 to your computer and use it in GitHub Desktop.
Save mittenchops/5984652 to your computer and use it in GitHub Desktop.
Flattens a nested list into a single list
# from http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
# DEPRECATED METHOD THAT WORKS REALLY WELL!
# http://stackoverflow.com/questions/16176742/python-3-replacement-for-deprecated-compiler-ast-flatten-function
# from compiler.ast import flatten
# flatten(["junk",["nested stuff"],[],[[]]])
# ['junk', 'nested stuff']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment