Anonymous user
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.
<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
[1, 2, 3, 4, 5, 6, 7, 8]</lang>
|