Skip to content

Instantly share code, notes, and snippets.

@defrank
Created July 2, 2017 02:51
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 defrank/36fc7fc0e1013a5e005a6b87800686f4 to your computer and use it in GitHub Desktop.
Save defrank/36fc7fc0e1013a5e005a6b87800686f4 to your computer and use it in GitHub Desktop.
Flatten a sequence in Python 3
#!/usr/bin/env python3
def flatten(myseq):
"""Lazily flatten a given sequence."""
for x in myseq:
if isinstance(x, (list, tuple, set, dict)):
yield from flatten(x)
else:
yield x
if __name__ == '__main__':
nested = [4, 5, 'hello', [6, 7, [8, 4, 3, 6],
2, [5, 7, [3, 2, 6], 2], 12], 42, [3, 5]]
# Explicitly want a flattened list.
flattened = list(flatten(nested))
# Sanity checks.
assert nested != flattened
assert len(flattened) > len(nested)
print('nested:', nested)
print('flattened:', flattened)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment