Skip to content

Instantly share code, notes, and snippets.

@rjnienaber
Created November 14, 2017 00:29
Show Gist options
  • Select an option

  • Save rjnienaber/4a067470e29fc169429aa4fa1c0a899b to your computer and use it in GitHub Desktop.

Select an option

Save rjnienaber/4a067470e29fc169429aa4fa1c0a899b to your computer and use it in GitHub Desktop.

Revisions

  1. rjnienaber created this gist Nov 14, 2017.
    22 changes: 22 additions & 0 deletions py3_flatten.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    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