Skip to content

Instantly share code, notes, and snippets.

@ojengwa
Created February 17, 2016 09:34
Show Gist options
  • Save ojengwa/862831cdd23b62e84dd6 to your computer and use it in GitHub Desktop.
Save ojengwa/862831cdd23b62e84dd6 to your computer and use it in GitHub Desktop.
Will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
import itertools
def flatten(iterable):
iterable = iter(iterable)
while True:
try:
item = iterable.next()
except StopIteration as e:
break
try:
data = iter(item)
iterable = itertools.chain(data, iterable)
except:
yield item
# To use:
# array = [[1,2,[3, [5]]],[4]]
# merged = flatten(array)
# next(merged) will lazily yeild the next element in the sequence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment