Flatten a list: Difference between revisions

→‎Recursive: Updated algorithm. New version is more readable, more idiomatic, and 3 times faster.
(Nimrod -> Nim)
(→‎Recursive: Updated algorithm. New version is more readable, more idiomatic, and 3 times faster.)
Line 2,107:
===Recursive===
 
This implementation of <code>flatten</code> preserves its argument. The <code>results</code> list is passed through all recursive calls.
Function <code>flatten</code> is recursive and preserves its argument:
<lang python>>>> def flatten(lst):
return sum( ([x] if not isinstance(x, list) else flatten(x)
for x in lst), [] )
 
<lang python>>>> def flatten(lst, results=[]): # 'results' defaults to an empty list []
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
for e in lst: # for each element 'e' in lst
>>> flatten(lst)
if type(e) is list: # if that element is a list, then
flatten(e, results) # flatten that sublist, appending results to "results"
else: # if it's not a list, then
results.append(x) # insert a copy of it at the end of "results"
return results
 
>>> lstl = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flatten(lstl)
[1, 2, 3, 4, 5, 6, 7, 8]</lang>