In the previous article, we have seen how to clone or Copy a list, now let’s see how to copy a nested list in Python. Method #1: Using Iteration
Python3
# Python program to copy a nested list # List initialization Input_list = [[ 0 , 1 , 2 ], [ 3 , 4 , 5 ], ] Output = [] # Using iteration to assign values for x in range ( len (Input_list)): temp = [] for elem in Input_list[x]: temp.append(elem) Output.append(temp) # Printing Output print ("Initial list is :") print (Input_list) print ("New assigned list is ") print (Output) |
Initial list is: [[0, 1, 2], [3, 4, 5]] New assigned list is [[0, 1, 2], [3, 4, 5]]
Method #2: Using deepcopy
Python3
# Python program to copy a nested list import copy # List initialization Input = [[ 1 , 0 , 1 ], [ 1 , 0 , 1 ]] # using deepcopy Output = copy.deepcopy( Input ) # Printing print ("Initial list is :") print ( Input ) print ("New assigned list is ") print (Output) |
Initial list is: [[1, 0, 1], [1, 0, 1]] New assigned list is [[1, 0, 1], [1, 0, 1]]
Method #3: Using list comprehension and slicing
Python3
# Python program to copy a nested list # List initialization Input_list = [[ 0 , 1 , 2 ], [ 3 , 4 , 5 ], [ 0 , 1 , 8 ]] # comprehensive method out_list = [ele[:] for ele in Input_list] # Printing Output print ("Initial list is :") print (Input_list) print ("New assigned list is ") print (out_list) |
Initial list is: [[0, 1, 2], [3, 4, 5], [0, 1, 8]] New assigned list is [[0, 1, 2], [3, 4, 5], [0, 1, 8]]
Method #4: Using the json module: The json module can be used to serialize and deserialize data in JSON format. This means that you can convert the nested list to a JSON string, and then parse the string to create a new list. This method can be useful if the elements in the nested list are serializable, but may not be suitable if the elements are not serializable.
Python3
import json # List initialization Input_list = [[ 0 , 1 , 2 ], [ 3 , 4 , 5 ]] # Convert the list to a JSON string json_str = json.dumps(Input_list) # Parse the JSON string to create a new list Output = json.loads(json_str) # Printing Output print ( "Initial list is:" ) print (Input_list) print ( "New assigned list is" ) print (Output) |
Initial list is: [[0, 1, 2], [3, 4, 5]] New assigned list is [[0, 1, 2], [3, 4, 5]]
The time complexity of the json method for copying a nested list is O(n), where n is the number of elements in the list. This is because it involves iterating over the elements of the list and serializing or deserializing them.
The space complexity of the json method is O(n), because it involves creating a new list and storing it in memory. It may also require additional space to store the JSON string representation of the list, which could be larger than the original list depending on the data type and size of the elements. However, the space complexity may be lower if the elements in the list are small and can be efficiently serialized.