Skip to content

Instantly share code, notes, and snippets.

@nathan-cruz77
Created December 16, 2023 18:40
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 nathan-cruz77/8d4a305d643144edaff371d5942fe4ea to your computer and use it in GitHub Desktop.
Save nathan-cruz77/8d4a305d643144edaff371d5942fe4ea to your computer and use it in GitHub Desktop.
Flattens nested lists/tuples into a single flat list.
# Flattens nested lists/tuples into a single flat list. Other typles are
# returned as-is.
#
#
# Sample usage:
#
# >>> flatten([1, 2, 3, 4])
# [1, 2, 3, 4]
#
# >>> flatten([1, [2, 3], 4])
# [1, 2, 3, 4]
#
# >>> flatten([1, [2, [3]], 4])
# [1, 2, 3, 4]
#
# >>> flatten((1, (2, [3]), 4))
# [1, 2, 3, 4]
#
# >>> flatten((1, (2, (3)), 4))
# [1, 2, 3, 4]
#
# >>> flatten((1, (2, (3)), {'a': 1}, 4))
# [1, 2, 3, {'a': 1}, 4]
#
def flatten(l):
if not isinstance(l, list) and not isinstance(l, tuple) :
return [l]
resulting_list = []
for item in l:
resulting_list.extend(flatten(item))
return resulting_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment