Skip to content

Instantly share code, notes, and snippets.

@Ricks-Lab
Last active March 27, 2021 11:17
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 Ricks-Lab/69e053f6604f33a2f0c0cc09a54049d8 to your computer and use it in GitHub Desktop.
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.
#!/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()
@Ricks-Lab
Copy link
Author

Ricks-Lab commented Mar 26, 2021

Output for the test cases:

[1, [2, 3]] -> [1, 2, 3]
[[1, 2], [3, 4]] -> [1, 2, 3, 4]
1 -> [1]
[1, [2, 3, (4, '5', 6, [7, 8, '9'])]] -> [1, 2, 3, 4, '5', 6, 7, 8, '9']
'a' -> ['a']

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