Skip to content

Instantly share code, notes, and snippets.

@saurabh-hirani
Last active January 16, 2019 09:21
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 saurabh-hirani/6f3d7f242d4423f9d2d5f9de4b5a5277 to your computer and use it in GitHub Desktop.
Save saurabh-hirani/6f3d7f242d4423f9d2d5f9de4b5a5277 to your computer and use it in GitHub Desktop.
Flatten a nested array
def flatten(arr):
"""
Flatten a nested array
>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten([1,2,3,[1,2,3]])
[1, 2, 3, 1, 2, 3]
>>> flatten([1,2,3,[1,2,[4,5,6],3]])
[1, 2, 3, 1, 2, 4, 5, 6, 3]
"""
flattened_arr = []
for elem in arr:
if not isinstance(elem, list):
flattened_arr.append(elem)
else:
[flattened_arr.append(i) for i in flatten(elem)]
return flattened_arr
if __name__ == "__main__":
import doctest
doctest.testmod()
@saurabh-hirani
Copy link
Author

This problem could also be a good use case for the yield statement.

@dhavalmetrani
Copy link

Neat! Was looking for this. Good to learn about doctest as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment