Copying Nested Lists in Python

Copying nested lists in Python

For a more general solution that works regardless of the number of dimensions, use copy.deepcopy():

import copy
b = copy.deepcopy(a)

python copying nested lists

One way to copy nested lists (given your example) is:

def deepcopy_nested_list(data):
out = []
for el in data:
if isinstance(el, list):
out.append(deepcopy_nested_list(el))
else:
out.append(el)
return out

This function copies the list to a new list and then recursively copies all nested lists to achieve a deep copy.

Please note that this does only create copies of lists and immutable objects (e.g., dicts are not copied). It shows only the idea how you would implement such a function and does not give a full implementation.

In real world code you would of course use copy.deepcopy().

Deep copy nested list without using the deepcopy function

My entry to simulate copy.deepcopy:

def deepcopy(obj):
if isinstance(obj, dict):
return {deepcopy(key): deepcopy(value) for key, value in obj.items()}
if hasattr(obj, '__iter__'):
return type(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.

Python copy a list of lists

From the docs for the copy module:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

When you call regular copy.copy() you are performing a shallow copy. This means that in a case of a list-of-lists, you will get a new copy of the outer list, but it will contain the original inner lists as its elements. Instead you should use copy.deepcopy(), which will create a new copy of both the outer and inner lists.

The reason that you didn't notice this with your first example of using copy([1,2]) is that the primitives like int are immutable, and thus it is impossible to change their value without creating a new instance. If the contents of the list had instead been mutable objects (like lists, or any user-defined object with mutable members), any mutation of those objects would have been seen in both copies of the list.

copying items from a nested list to more than one list

Alright, sorry for the bad question format.
Anyways, here is the solution to my question:
the solution is fairly simple, all what happened is that I added an unneeded extra for loop for index in lists which unnessecarily added extra items to my list. the solution is as follows

row_1 = []
row_2 = []
row_3 = []
for lists in inputs:
row_1.append(lists[0])
row_2.append(lists[1])
row_3.append(lists[2])

and if we continue with the example input above inputs = [[1,0,1], [1,1,1]]
We do indeed get our desired output [1, 1] [0, 1] [1, 1]

to anyone who landed on this same question, just try and add a debugger under your tool belt, would be really useful. If not viable, don't get discouraged from the error, take a break and you will most likely figure it out.

Copy values from one nested list into another empty nested list

When doing:

for i in M:

The value of i will always be the value of the array in a given location.

You want the actual index, so loop through a range from 0 to the length of the index.

for i in range(0, len(M)):
if len(M[i]) == 0:
M[i] = L[i]

Python: append copy of nested list to list

from copy import deepcopy

pastmoves.append(deepcopy(gamelist))

Copy of nested list gets bigger when appending to original

as mentioned in the comment list.copy() is shallow, a solution would be to use the deepcopy method from copy library

import copy
...
temp=copy.deepcopy(matrixInput)


Related Topics



Leave a reply



Submit