Skip to content

Instantly share code, notes, and snippets.

@rjnienaber
Created November 14, 2017 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjnienaber/4a067470e29fc169429aa4fa1c0a899b to your computer and use it in GitHub Desktop.
Save rjnienaber/4a067470e29fc169429aa4fa1c0a899b to your computer and use it in GitHub Desktop.
Simple example of flattening an array in python3
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