# python flatten arbitrarily nested list

January 1st,
2021

Hi Mitch @Helvetosaur. import matplotlib l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] print(list(matplotlib.cbook.flatten(l))) l2 = [[1, 2, 3], [4, 5, 6], [7], [8, [9, 10, [11, 12, [13]]]]] print list(matplotlib.cbook.flatten(l2)) Result: It works for lists that have a maximum depth of nesting roughly equal to the recursion depth limit of Python, which is set to 1000 by default, though it can be increased with sys.setrecursionlimit().

# Program to flatten an arbitrarily nested list. So I convert my units to a nested list of subunits. That post also has multiple comments that show or link to alternative solutions, including some that use Python 3 features like "yield from". The old way would be to do this using a couple of loops one inside the other. Works with arbitrary nested-lists whose elements are either nested-lists, or non-nested lists of atoms, or atoms (subjected to recursion limit). Sometimes you need to flatten a list of lists. © 2020 ActiveState Software Inc. All rights reserved. Regular List of Lists Known issue: the solution uses a recursive flatten() function, which will not work if the depth of recursion exceeds about 1000. I consider these results to be a myth-buster, because they are not at all what I expected based on what we consider best practice in the Python community. (2) Here's a recursive approach that is string friendly: ... Possible Duplicate: Flattening a shallow list in Python Flatten (an irregular) list of lists in Python. Arbitrary depth recursion, necessary for arbitrarily nested lists does not function well with Python's conservative maximum recursion depth. from copy import deepcopy. \\$\begingroup\\$ Sorry if that was confusing, they're just different versions.