Flatten a list: Difference between revisions

Content deleted Content added
Ce (talk | contribs)
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
i=0
while i<len(lst):
while i<len(lst):
while True:
while True:
try:
try:
lst[i:i+1] = lst[i]
lst[i:i+1] = lst[i]
except (TypeError, IndexError):
except (TypeError, IndexError):
break
break
i += 1
i += 1
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flat(lst)
>>> flat(lst)