Python How to copy a nested list

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to see different ways to copy a nested list in Python. Let's see one by one.

First, we will copy the nested list using loops. And it's the most common way.

Example

 Live Demo

# initializing a list
nested_list = [[1, 2], [3, 4], [5, 6, 7]]
# empty list
copy = []
for sub_list in nested_list:
   # temporary list
   temp = []
   # iterating over the sub_list
   for element in sub_list:
      # appending the element to temp list
      temp.append(element)
   # appending the temp list to copy
   copy.append(temp)
# printing the list
print(copy)

Output

If you run the above code, then you will get the following result.

[[1, 2], [3, 4], [5, 6, 7]]

Let's see how to copy nested list using list comprehension and unpacking operator.

Example

 Live Demo

# initializing a list
nested_list = [[1, 2], [3, 4], [5, 6, 7]]
# copying
copy = [[*sub_list] for sub_list in nested_list]
# printing the copy
print(copy)

Output

If you run the above code, then you will get the following result.

[[1, 2], [3, 4], [5, 6, 7]]

Now, let's see another way to copy nested list. We will have methods called deepcopy from copy module to copy nested lists. Let's see it.

Example

 Live Demo

# importing the copy module
import copy
# initializing a list
nested_list = [[1, 2], [3, 4], [5, 6, 7]]
# copying
copy = copy.deepcopy(nested_list)
# printing the copy
print(copy)

Output

If you run the above code, then you will get the following result.

[[1, 2], [3, 4], [5, 6, 7]]

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.

raja
Published on 07-Jul-2020 08:52:57
Advertisements