Skip to content

Instantly share code, notes, and snippets.

@dppereyra
Last active July 12, 2017 14:36
Show Gist options
  • Save dppereyra/178605e04b330547eda5d96dfc1722cb to your computer and use it in GitHub Desktop.
Save dppereyra/178605e04b330547eda5d96dfc1722cb to your computer and use it in GitHub Desktop.
Flatten List
def flatten1(list_):
'''Flatten nested list of integers into a single list.
Args:
list_ (list): list to be flattened
Returns:
Iterable[int]: the flattened list.
'''
result = []
for item in list_:
if isinstance(item, list):
result = result + flatten1(item)
else:
result.append(item)
return result
def flatten2(list_):
'''Same as flatten1 but outputs as a generator in order to handle very
large lists.
Args:
list_ (list): list to be flattened
Returns:
Generator[int, None, None]: the flattened list.
'''
for item in list_:
if isinstance(item, list):
yield from flatten2(item)
else:
yield item
# Uses PyTest Testing Format
from source import flatten1, flatten2
def test_flatten():
testcase = [[1,2,[3]],4,[[5, 6], 7]]
funcs = (flatten1, flatten2)
for func in funcs:
result = func(testcase)
for item in result:
assert not isinstance(item, list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment