Last active
March 27, 2021 11:17
-
-
Save Ricks-Lab/69e053f6604f33a2f0c0cc09a54049d8 to your computer and use it in GitHub Desktop.
A function to flatten an arbitrary list of lists, tuples, and other elements using recursion and list comprehension.
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
#!/usr/bin/python3 | |
""" Demo of recursive list comprehension to flatten arbitrary list of lists and other objects. | |
""" | |
from typing import Any | |
def flatten_list(source: Any) -> list: | |
""" Flatten arbitrary list of lists or tuples to a simple list of elements. This method works | |
even if the list contains non-list objects. | |
""" | |
if isinstance(source, (list, tuple)): | |
return [item for sub_list in source for item in flatten_list(sub_list)] | |
new_list = [] | |
new_list.append(source) | |
return new_list | |
def main(): | |
""" Demo of flatten_list | |
""" | |
test_cases = [[1, [2, 3]], | |
[[1, 2], [3, 4]], | |
1, | |
[1, [2, 3, (4, '5', 6, [7, 8, '9'])]], | |
'a'] | |
for test_case in test_cases: | |
print('{} -> {}'.format(test_case, flatten_list(test_case))) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output for the test cases: