Skip to content

Instantly share code, notes, and snippets.

@zshn25
Created May 28, 2024 12:48
Show Gist options
  • Save zshn25/5869e16b8fe436213414208d445a58cb to your computer and use it in GitHub Desktop.
Save zshn25/5869e16b8fe436213414208d445a58cb to your computer and use it in GitHub Desktop.
Python utils
from typing import Iterable
#from collections import Iterable # < py38
def flatten(items):
"""Yield items from any nested iterable;
Source: https://stackoverflow.com/a/40857703
Usage:
complicated = [[1, [2]], (3, 4, {5, 6}, 7), 8, "9"] # numbers, strs, nested & mixed
list(flatten(complicated))
# [1, 2, 3, 4, 5, 6, 7, 8, '9']
"""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
for sub_x in flatten(x):
yield sub_x
else:
yield x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment