Open In App

Python | How to copy a nested list

Last Updated : 05 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Copying a nested list in Python involves preserving both the structure and values of the original. One common method is using copy.deepcopy() from the copy module. Additionally, list comprehensions with slicing offer a concise approach for creating an independent duplicate. 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.

Copy a Nested List in Python

Below are the ways by which we can copy a nested list in Python:

  • Using Iteration 
  • Using deepcopy 
  • Using list comprehension and slicing 
  • Using the json module

Copy a Nested List Using Iteration

In this example, the code iterates through a nested list (Input_list) using nested loops to create a new list (Output). The inner loop assigns values to a temporary list, which is then appended to the outer list, resulting in a copy of the structure of the original nested list.

Python3




# 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)


Output

Initial list is:
[[0, 1, 2], [3, 4, 5]]
New assigned list is
[[0, 1, 2], [3, 4, 5]]

Time Complexity: O(n), where n is the number of elements in the list.
Space Complexity: O(n)

Python Copy a Nested List Using Deepcopy 

In this example, a nested list Input is duplicated to Output using copy.deepcopy() to ensure an independent copy of both the outer and inner list elements. The program then prints the initial and newly assigned lists for verification.

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)


Output

Initial list is:
[[1, 0, 1], [1, 0, 1]]
New assigned list is
[[1, 0, 1], [1, 0, 1]]

Time Complexity: O(n), where n is the number of elements in the list.
Space Complexity: O(n)

Copy a Nested List Using List Comprehension and Slicing

In this example, a nested list Input_list is efficiently duplicated to out_list using a list comprehension and slicing. This method creates a new list with the same structure and values, as demonstrated by printing both the initial and newly assigned lists.

Python3




# 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)


Output

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]]

Time Complexity: O(n), where n is the number of elements in the list.
Space Complexity: O(n)

How to Copy a Nested List 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)


Output

Initial list is:
[[0, 1, 2], [3, 4, 5]]
New assigned list is
[[0, 1, 2], [3, 4, 5]]


Time Complexity: O(n), where n is the number of elements in the list.
Space Complexity: O(n)



Previous Article
Next Article

Similar Reads

copy in Python (Deep Copy and Shallow Copy)
In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use the = operator, It only creates a new variable that shares the reference of the original object. In order to create "real copies" or "clones" of these objects, we can use the copy module in Python. Syntax of Python DeepcopySyntax:
5 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Copy a Python Dictionary and only Edit the Copy
Copying a dictionary in Python to preserve the original while making changes to the duplicate is a common task. Developers use methods like the `copy` module or the dictionary's `copy()` method to create an independent duplicate, allowing for isolated edits. This article explores commonly used techniques to copy a dictionary and modify only the dup
4 min read
Python Dictionary Copy Vs Deep Copy
In Python, Dictionary like other non-primitive data structures can be copied using various methods. The key distinction lies in the depth of the copy. In this article, we are going to learn about deep copy and shallow copy in Python. What is Shallow Copy in Python Dictionary?In Python, a shallow copy creates a new object that references the same un
3 min read
Difference Between Shallow copy VS Deep copy in Pandas Dataframes
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
Shallow copy vs Deep copy in Pandas Series
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
NumPy ndarray.copy() Method | Make Copy of a Array
The ndarray.copy() method returns a copy of the array. It is used to create a new array that is a copy of an existing array but does not share memory with it. This means that making any changes to the original array won't affect the existing array. Example C/C++ Code # Python program explaining # numpy.ndarray.copy() function import numpy as geek x
2 min read
Python | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the solution of this problem. Method #1 : Using zip()
10 min read
Python | Find maximum length sub-list in a nested list
Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form (list, list_length). Examples: Input : [['A'], ['A', 'B'], ['A', 'B', 'C']] Output : (['A', 'B', 'C'], 3) Input : [[1, 2, 3, 9, 4], [5], [3, 8], [2]] Output : ([1, 2, 3, 9, 4], 5) Let's discuss different approaches to solve this prob
3 min read
Python | Convert string List to Nested Character List
Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() The combination of above functional
7 min read
Practice Tags :
three90RightbarBannerImg