Skip to content

Instantly share code, notes, and snippets.

@ishikawa
Created August 28, 2010 03:19
Show Gist options
  • Save ishikawa/554641 to your computer and use it in GitHub Desktop.
Save ishikawa/554641 to your computer and use it in GitHub Desktop.
iterate_recursively: flatten a list easily
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