Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flatten an arbitrarily nested array
def flatten(items):
"""
Flatten a nested list of integers.
Passing a non-list instead returns a list containing the argument.
"""
if not isinstance(items, list):
return [items]
result = []
for i in items:
for x in flatten(i):
result.append(x)
return result
# Use pytest to run this function.
def test_flatten():
assert flatten(10) == [10]
assert flatten([3]) == [3]
assert flatten([4, 2, 5]) == [4, 2, 5]
assert flatten([1, 2, [3, 4]]) == [1, 2, 3, 4]
assert flatten([[1], [2, 4, [5, 2]], 31, [15, 2]]) == [1, 2, 4, 5, 2, 31, 15, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.