Skip to content

Instantly share code, notes, and snippets.

@apackeer
Created September 30, 2012 06:56
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 apackeer/3806095 to your computer and use it in GitHub Desktop.
Save apackeer/3806095 to your computer and use it in GitHub Desktop.
Flatten a list
def flatten(list_):
nested = True
while nested:
iter_ = False
temp = []
for element in list_:
if isinstance(element, list):
temp.extend(element)
iter_ = True
else:
temp.append(element)
nested = iter_
list_ = temp[:]
return list_
# Example:
# flatten(["test", ["test1", "test2", ["test", "test1"], "test3"], "test4"] -> ["test", "test1", "test2", "test", "test1", "test3", "test4"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment