Skip to content

Instantly share code, notes, and snippets.

@GaryLee
Last active June 21, 2024 02:29
Show Gist options
  • Save GaryLee/713f2c8a8ce260498ff0f496d32062b8 to your computer and use it in GitHub Desktop.
Save GaryLee/713f2c8a8ce260498ff0f496d32062b8 to your computer and use it in GitHub Desktop.
Flatten nested Python sequence object.
from collections.abc import Sequence
def flatten(x):
"""Flatten given parameter recursively."""
if isinstance(x, Sequence):
for v in x:
yield from flatten(v)
else:
yield x
if __name__ == '__main__':
data = [1,2,[[3,4],5,[2,[3,4,5]]],[6,7],100,]
print(list(flatten(data)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment