Skip to content

Instantly share code, notes, and snippets.

@alexland
Last active December 24, 2015 17:29
Show Gist options
  • Save alexland/6835638 to your computer and use it in GitHub Desktop.
Save alexland/6835638 to your computer and use it in GitHub Desktop.
flatten a nested sequence: distinguishes lists from strings, etc.
# first, a compact one-liner but limited to 2D sequences (nested just one level):
# obvious, but
# "nested_list" refers to the nested list you want to flatten,
# "row" refers to each list comprising the nested_list
# "itm" refers to each element comprising each row
def flatten(list2D):
return [itm for row in list2d for itm in row]
# explanation: derive the list comprehension above from the loop syntax:
flat_list = []
for row in nested_list:
for itm in row:
flat_list.append(itm)
# ie, just copy the loop syntax into the list comprehension:
# "for row in nested list for itm in row"
# then add the antecedent (itm):
# "itm for row in nested list for itm in row"
def flatten_nested_seq(nested_seq, ignore_seq=(str, bytes)):
"""
returns: generator w/ all items from nested_seq
pass in: nested_seq, eg, list
"""
import collections as CL
for itm in nested_seq:
if isinstance(itm, CL.Iterable) and not isinstance(itm, ignore_seq):
yield from flatten_nested_seq(itm)
else:
yield itm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment