Skip to content

Instantly share code, notes, and snippets.

@gvoysey
Last active November 30, 2022 22:36
Show Gist options
  • Select an option

  • Save gvoysey/fae92b70645b6490e793f0b723bf9bdf to your computer and use it in GitHub Desktop.

Select an option

Save gvoysey/fae92b70645b6490e793f0b723bf9bdf to your computer and use it in GitHub Desktop.
recursively flatten nested iterables without fucking up stringlikes.
from collections.abc import Iterable
def should_flatten(x):
return isinstance(x, Iterable) and not isinstance(x, (str, bytes))
def flatten(x, should_flatten=should_flatten):
for y in x:
if should_flatten(y):
yield from flatten(y, should_flatten=should_flatten)
else:
yield y
@gvoysey
Copy link
Author

gvoysey commented Aug 15, 2019

h/t @altendky

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment