Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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(bad):
flat = []
while bad:
element = bad.pop()
if isinstance(element, list):
bad.extend(element)
else:
flat.append(element)
flat.reverse()
return flat
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
Something went wrong with that request. Please try again.