# Created on savesnippets.com ยท https://savesnippets.com/5k2H9tY0vbEi8B 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]