Flatten nested data

111
6
Tuesday
DanPatterson
MVP Esteemed Contributor
2 6 111

Replace the numbers below with anything you want.

lst = [
       [[1, 2, 3], [4, 5]],
       [[1, 2]],
       [1, 2],
       [[]],
       [[1, 2, 3], [4, 5], [6, 7, 8]],
       [[[1, 2, 3], [4, 5]], [[6, 7, 8]]],
       ]

 

Flatten with recursion (a function calling itself 'recursively')

def flatten(a_list, flat_list=None):
    """Change the isinstance as appropriate.

    :  Flatten an object using recursion
    :  see: itertools.chain() for an alternate method of flattening.
    """
    if flat_list is None:
        flat_list = []
    for item in a_list:
        if isinstance(item, list):
            flatten(item, flat_list)
        else:
            flat_list.append(item)
    return flat_list

 

Simple flattening

flatten(lst)

[1, 2, 3, 4, 5, 1, 2, 1, 2, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]

Who says you can't start out with initial values.

flatten(lst, ['a', 'b']))
['a', 'b', 1, 2, 3, 4, 5, 1, 2, 1, 2, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]

6 Comments
About the Author
Retired Geomatics Instructor (also DanPatterson_Retired). Currently working on geometry projects (various) as they relate to GIS and spatial analysis. I use NumPy, python and kin and interface with ArcGIS Pro.
Labels