Skip to content

Instantly share code, notes, and snippets.

@seanwu1105
Forked from ma-ric/flatten.py
Created July 14, 2018 02:26
Show Gist options
  • Save seanwu1105/9b91643a025d95aaf09e2c1cbaebc864 to your computer and use it in GitHub Desktop.
Save seanwu1105/9b91643a025d95aaf09e2c1cbaebc864 to your computer and use it in GitHub Desktop.
Python; recursive flatten of nested iterables, with proper handling of string elements
#!/usr/bin/env python3
import collections
def flatten(t):
"""
Generator flattening the structure
>>> list(flatten([2, [2, "test", (4, 5, [7], [2, [6, 2, 6, [6], 4]], 6)]]))
[2, 2, "test", 4, 5, 7, 2, 6, 2, 6, 6, 4, 6]
"""
for x in t:
if isinstance(x, str) or not isinstance(x, collections.Iterable):
yield x
else:
yield from flatten(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment