from typing import Iterable, Iterator, Any
def flatten(items: Iterable[Any]) -> Iterator[Any]:
for item in items:
if isinstance(item, (list, tuple)) and not isinstance(item, (str, bytes)):
yield from flatten(item)
else:
yield item
list(flatten([1, [2, [3, 4]], 5])) # [1, 2, 3, 4, 5]
list(flatten(["a", ["b", ["c"]]])) # ['a', 'b', 'c'] (strings stay whole)
list(flatten([[1, 2], (3, [4, 5])])) # [1, 2, 3, 4, 5]
Create a free account and build your private vault. Share publicly whenever you want.