Skip to content

Instantly share code, notes, and snippets.

@shaxbee
Forked from mrluanma/flatten.py
Last active August 29, 2015 14:09
Show Gist options
  • Save shaxbee/0ada767debf9eefbdb6e to your computer and use it in GitHub Desktop.
Save shaxbee/0ada767debf9eefbdb6e to your computer and use it in GitHub Desktop.
How to flatten a python nested list(tuple) - generator
#!/usr/bin/env python3
import collections
def flatten(t):
"""
Generator flattening the structure
>>> list(flatten([2, [2, (4, 5, [7], [2, [6, 2, 6, [6], 4]], 6)]]))
[2, 2, 4, 5, 7, 2, 6, 2, 6, 6, 4, 6]
"""
for x in t:
if 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