Skip to content

Instantly share code, notes, and snippets.

@andresmachado
Last active February 23, 2018 01:43
Show Gist options
  • Save andresmachado/4ca728cc5ce6a58a699be25a36144ac8 to your computer and use it in GitHub Desktop.
Save andresmachado/4ca728cc5ce6a58a699be25a36144ac8 to your computer and use it in GitHub Desktop.
List Flatten
import collections
alist = [[1, 2, [3, [5, 6, 7]]], 4]
def flat_list(xs):
for x in xs:
if isinstance(x, str) or not isinstance(x, collections.Iterable):
yield x
else:
yield from flat_list(x)
print(list(flat_list(alist)))
assert list(flat_list(alist)) == [1, 2, 3, 5, 6, 7, 4]
assert list(flat_list([1, 2, 3, 4, 5])) == [1, 2, 3, 4, 5]
assert list(flat_list((1, 3, 5, [4, 5, 6, 'a']))) == [1, 3, 5, 4, 5, 6, 'a']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment