Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Generator Version solution in Clear category for Flatten a List (generator version) by Stensen
def isiterable(x):
try: iter(x)
except TypeError: return False
return True
def flat_list(l):
for e in l:
if isiterable(e) and not isinstance(e, str):
for subl in flat_list(e): yield subl
else: yield e
if __name__ == '__main__':
assert list(flat_list([1, 2, 3])) == [1, 2, 3], "First"
assert list(flat_list([1, [2, 2, 2], 4])) == [1, 2, 2, 2, 4], "Second"
assert list(flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]])) == [2, 4, 5, 6, 6, 6, 6, 6, 7], "Third"
assert list(flat_list([-1, [1, [-2], 1], -1])) == [-1, 1, -2, 1, -1], "Four"
print('Done! Check it')
Sept. 24, 2020