Skip to content

Instantly share code, notes, and snippets.

@gboeer
Last active February 21, 2024 09:26
Show Gist options
  • Save gboeer/a32085ee703ac2aeebd5e3443231eaa9 to your computer and use it in GitHub Desktop.
Save gboeer/a32085ee703ac2aeebd5e3443231eaa9 to your computer and use it in GitHub Desktop.
Flattens a nested list of arbitrary depth into a flat list.
def flatten(lst):
"""
Flattens a nested list of arbitrary depth into a flat list.
This function recursively traverses each element in a list. If an element is a list,
it is further flattened. This continues until no nested lists remain, producing a
flat list containing all non-list elements from the original nested structure.
Parameters:
- lst (list): The list to be flattened. Can contain nested lists of arbitrary depth.
Returns:
- generator: A generator yielding elements of the flattened list.
Examples:
>>> list(flatten([1, [2, 3], [4, [5, 6, [7, 8]], 9], 10]))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(flatten([[1, 2], [3, [4, 5]], 6]))
[1, 2, 3, 4, 5, 6]
>>> list(flatten(['a', ['b', 'c', ['d']], 'e']))
['a', 'b', 'c', 'd', 'e']
"""
for item in lst:
if isinstance(item, list):
yield from flatten(item) # If the item is a list, recurse
else:
yield item # If the item is not a list, yield it directly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment