Skip to content

Instantly share code, notes, and snippets.

@silveira
Last active March 17, 2017 16:49
Show Gist options
  • Save silveira/1229108 to your computer and use it in GitHub Desktop.
Save silveira/1229108 to your computer and use it in GitHub Desktop.
Examples of non-recursive function to flatten and sort a list. Keeping sorting by the way is greatly better because of timsort on Python.
#!/usr/bin/python
"""
Flatten a list
"""
def flatten(notflat):
flat = []
while notflat:
element = notflat.pop()
if isinstance(element, list):
notflat.extend(element)
else:
flat.append(element)
return flat.reverse()
if __name__ == "__main__" :
test = [1,2,[3,4],[5,6], [7], 8, [[[[1]]]], 2,3,[1,[2,[3],5],[7,[8],9]], [1,[2],[1,2,3,4]]]
print flatten(test)
# [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 1, 2, 3, 5, 7, 8, 9, 1, 2, 1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment