Last active
February 23, 2018 01:43
-
-
Save andresmachado/4ca728cc5ce6a58a699be25a36144ac8 to your computer and use it in GitHub Desktop.
List Flatten
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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