Skip to content

Instantly share code, notes, and snippets.

@chisler
Last active April 11, 2019 20:59
Show Gist options
  • Save chisler/b1188c176e7ea09aefa74fae0487183f to your computer and use it in GitHub Desktop.
Save chisler/b1188c176e7ea09aefa74fae0487183f to your computer and use it in GitHub Desktop.
Second One
"""
Create an iterator that yields elements of nested list.
"""
class FlatIterator:
def __init__(self, data):
self.stack = [iter(data)]
def __iter__(self):
return self
def __next__(self):
if not self.stack:
raise StopIteration
current = self.stack.pop()
try:
element = next(current)
self.stack.append(current)
if isinstance(element, list):
self.stack.append(iter(element))
# If we've found a list,
# we need to iterate it instead
return next(self)
else:
return element
except StopIteration:
# If current iterator has finished
# We need to try next one
return next(self)
a = [
[1, 2, 3],
[4, [5], 6],
[],
[[7]]
]
flat = FlatIterator(a)
assert [i for i in flat] == list(range(1, 8))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment