Created
December 16, 2023 18:40
-
-
Save nathan-cruz77/8d4a305d643144edaff371d5942fe4ea to your computer and use it in GitHub Desktop.
Flattens nested lists/tuples into a single flat list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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