Last active
December 20, 2020 15:06
-
-
Save Wilfred/7889868 to your computer and use it in GitHub Desktop.
flatten an arbitrarily nested list in Python
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
from copy import deepcopy | |
def flatten_list(nested_list): | |
"""Flatten an arbitrarily nested list, without recursion (to avoid | |
stack overflows). Returns a new list, the original list is unchanged. | |
>> list(flatten_list([1, 2, 3, [4], [], [[[[[[[[[5]]]]]]]]]])) | |
[1, 2, 3, 4, 5] | |
>> list(flatten_list([[1, 2], 3])) | |
[1, 2, 3] | |
""" | |
nested_list = deepcopy(nested_list) | |
while nested_list: | |
sublist = nested_list.pop(0) | |
if isinstance(sublist, list): | |
nested_list = sublist + nested_list | |
else: | |
yield sublist |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
your solution is pretty good but the complexity of pop(0) is o(n) because you need to reorganize all the indices and the complexity you sum other list at the begin of the list and the complexity of that is o(n+m) we can improve those operations using a queue instead, the code is below