flatten_list()
Flatten an arbitrarily nested list into a single flat list.
Usage
flatten_list(nested)Recursively traverses the input list and collects all non-list elements into a single flat list.
Parameters
nested: list-
A potentially nested list of values.
Returns
list-
A flat list containing all leaf elements.
Notes
The function uses recursion to handle arbitrarily deep nesting. For each element in the input, it checks whether the element is itself a list. If so, it recurses into that sublist. Otherwise, the element is appended to the result.
Because Python has a default recursion limit of 1000, this function will raise a RecursionError for lists nested deeper than approximately 500 levels (accounting for the two-frame overhead per recursive call).
The implementation allocates a new list and extends it with each recursive result. The overall time complexity is O(n) where n is the total number of leaf elements, but the constant factor depends on the nesting depth due to intermediate list allocations.
Examples
>>> flatten_list([1, [2, [3, 4], 5], 6])
[1, 2, 3, 4, 5, 6]>>> flatten_list([[["deep"]]])
['deep']