Create a gist now

Instantly share code, notes, and snippets.

@silveira /flatten
Last active Mar 17, 2017

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