Created
August 28, 2010 03:19
-
-
Save ishikawa/554641 to your computer and use it in GitHub Desktop.
iterate_recursively: flatten a list easily
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 iterate_recursively(*objects): | |
""" | |
Makes an iterator that returns elements from the `objects` argument. | |
If an element is a list or tuple, the element will be iterated | |
recursively, and the iterator returns each items. | |
>>> list(iterate_recursively(1, 2, 3)) | |
[1, 2, 3] | |
>>> list(iterate_recursively([1, 2, 3])) | |
[1, 2, 3] | |
>>> list(iterate_recursively(1, [2, 3])) | |
[1, 2, 3] | |
>>> list(iterate_recursively(1, [2, [3]])) | |
[1, 2, 3] | |
>>> list(iterate_recursively([1], (2,(3)))) | |
[1, 2, 3] | |
""" | |
for object in objects: | |
if isinstance(object, (list, tuple)): | |
for element in iterate_recursively(*object): | |
yield element | |
else: | |
yield object |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment