Created
November 14, 2017 00:29
-
-
Save rjnienaber/4a067470e29fc169429aa4fa1c0a899b to your computer and use it in GitHub Desktop.
Simple example of flattening an array in python3
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
def _flatten(values): | |
"""Recursively flattens a list using yield from""" | |
for v in values: | |
if (isinstance(v, list)): | |
yield from _flatten(v) # https://www.python.org/dev/peps/pep-0380/ | |
else: | |
yield v | |
def flattened_list(values): | |
"""Recursively flattens a list. If the passed in argument is not a list, an | |
error is thrown.""" | |
if isinstance(values, list): | |
return list(_flatten(values)) | |
else: | |
raise ValueError('Passed in value must be a list') | |
if __name__ == '__main__': | |
print(flattened_list([[1,2,[3]],4]) == [1, 2, 3, 4]) | |
print(flattened_list([]) == []) | |
print(flattened_list(None)) # error thrown, should be a list | |
print(flattened_list("")) # error thrown, should be a list | |
print(flattened_list("123123")) # error thrown, should be a list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment