Skip to content

Instantly share code, notes, and snippets.

@marconi
Last active March 10, 2016 02:44
Show Gist options
  • Save marconi/b9f3e41c2ad79b9980bc to your computer and use it in GitHub Desktop.
Save marconi/b9f3e41c2ad79b9980bc to your computer and use it in GitHub Desktop.
Flatten arbitrarily nested arrays of integers.
import numbers
def flatten(xs):
"""
# Flatten arbitrarily nested arrays of integers
# e.g. [[1, 2, [3]], 4] -> [1, 2, 3, 4]
"""
# if not list, return single item list but only if its a number
if not isinstance(xs, list):
return [xs] if isinstance(xs, numbers.Number) else []
# otherwise, continue splitting by taking off the head,
# flattening it and prepend it back to the tail
return flatten(xs[0]) + (flatten(xs[1:]) if len(xs) > 1 else [])
if __name__ == '__main__':
assert flatten([[1, 2, [3]], 4]) == [1, 2, 3, 4]
assert flatten([[1, 2, [3]], 4, [5, [6, [7, 8, [9, [10]]]]]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert flatten([1, ['a', 2, 'b'], [3, 'c', ['d', 'e', 4]]]) == [1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment