Skip to content Skip to sidebar Skip to footer

"deep Copy" Nested List Without Using The Deepcopy Function

I am trying to copy the nested list a, but do not know how to do it without using the copy.deepcopy function. a = [[1, 2], [3, 4]] I used: b = a[:] and b = a[:][:] But they all

Solution 1:

My entry to simulate copy.deepcopy:

defdeepcopy(obj):
    ifisinstance(obj, dict):
        return {deepcopy(key): deepcopy(value) for key, value in obj.items()}
    ifhasattr(obj, '__iter__'):
        returntype(obj)(deepcopy(item) for item in obj)
    return obj

The strategy: iterate across each element of the passed-in object, recursively descending into elements that are also iterable and making new objects of their same type.

I make no claim whatsoever that this is comprehensive or without fault [1] (don't pass in an object that references itself!) but should get you started.

[1] Truly! The point here is to demonstrate, not cover every possible eventuality. The source to copy.deepcopy is 50 lines long and it doesn't handle everything.

Solution 2:

You can use a LC if there's but a single level.

b = [x[:] for x in a]

Solution 3:

This is a complete cheat - but will work for lists of "primitives" - lists, dicts, strings, numbers:

defcheat_copy(nested_content):
  returneval(repr(nested_content))

There are strong security implications to consider for this - and it will not be particularly fast. Using json.dumps and loads will be more secure.

Solution 4:

I found a way to do it using recursion.

defdeep_copy(nested_content):
    ifnotisinstance(nested_content,list):
        return nested_content
    else:
        holder = []
        for sub_content in nested_content:
            holder.append(deep_copy(sub_content))
        return holder

Solution 5:

For the recursive version, you have to keep track of a secondary list and return each time.

Post a Comment for ""deep Copy" Nested List Without Using The Deepcopy Function"