Created
July 2, 2017 02:51
-
-
Save defrank/36fc7fc0e1013a5e005a6b87800686f4 to your computer and use it in GitHub Desktop.
Flatten a sequence in Python 3
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
#!/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