How to make a completely unshared copy of a complicated list? (Deep copy is not enough)

To convert an existing list of lists to one where nothing is shared, you could recursively copy the list.

deepcopy will not be sufficient, as it will copy the structure as-is, keeping internal references as references, not copies.

def unshared_copy(inList):
    if isinstance(inList, list):
        return list( map(unshared_copy, inList) )
    return inList

alist = unshared_copy(your_function_returning_lists())

Note that this assumes the data is returned as a list of lists (arbitrarily nested).
If the containers are of different types (eg. numpy arrays, dicts, or user classes), you may need to alter this.

Leave a Comment