- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python How to copy a nested list
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
# 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
# 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
# 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.
Advertisements