Flattening and unflattening a nested list of numpy arrays <p>There are many recipes for flattening a nested list. I'll copy a solution here just for reference: </p> <pre><code>def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result </code></pre> <p>What I am interested in is the inverse operation, which reconstructs the list to its original format. For example:</p> <pre><code>L = [[array([[ 24, -134],[ -67, -207]])], [array([[ 204, -45],[ 99, -118]])], [array([[ 43, -154],[-122, 168]]), array([[ 33, -110],[ 147, -26],[ -49, -122]])]] # flattened version L_flat = [24, -134, -67, -207, 204, -45, 99, -118, 43, -154, -122, 168, 33, -110, 147, -26, -49, -122] </code></pre> <p>Is there an efficient way of flattening, saving indices and reconstructing to its original format?</p> <p>Note that the list can be of arbitrary depth and may not have a regular shape, and will contain arrays of differing dimensions.</p> <p>Of course, the flattening function should be also changed to store the structure of the list and the shape of the <code>numpy</code> arrays.</p>