Flatten a list: Difference between revisions
Content deleted Content added
added C++ |
→Non-recursive: Re-indent. |
||
Line 221: | Line 221: | ||
Function flat is iterative and flattens the list in-place. It follows the Python idiom of returning None when acting in-place: |
Function flat is iterative and flattens the list in-place. It follows the Python idiom of returning None when acting in-place: |
||
<lang python>>>> def flat(lst): |
<lang python>>>> def flat(lst): |
||
i=0 |
|||
while i<len(lst): |
|||
while True: |
|||
try: |
|||
lst[i:i+1] = lst[i] |
|||
except (TypeError, IndexError): |
|||
break |
|||
i += 1 |
|||
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] |
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] |
||
>>> flat(lst) |
>>> flat(lst) |