public
Created

Examples of non-recursive function to flatten and sort a list. Keeping sorting by the way is greatly better because of timsort on Python.

  • Download Gist
flatten
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#!/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]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.