Last active
August 3, 2016 01:08
-
-
Save adammartinez271828/2b84dc91fc54fb8871787b0c41175666 to your computer and use it in GitHub Desktop.
Flatten arbitrary nested lists
This file contains hidden or 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
| def flatten(iterable): | |
| """Return a generator that flattens an iterable | |
| Safe to use on nested iterables. | |
| Args: | |
| iterable: any iterable. | |
| Returns: | |
| generator of all items in iterable | |
| Example: | |
| >>> list(flatten([1, [2, 3], [4, [5, 6]]])) | |
| [1, 2, 3, 4, 5, 6] | |
| """ | |
| for element in iterable: | |
| try: | |
| yield from flatten(element) | |
| except TypeError: | |
| yield element | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment