
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- How to iterate through a nested List in Python?
- How to clone or copy a list in Python?
- Python - Convert List to custom overlapping nested list
- Python program to Flatten Nested List to Tuple List
- Python program to clone or copy a list.
- Python Program to Flatten a Nested List using Recursion
- Convert a nested list into a flat list in Python
- How to access nested Python dictionary items via a list of keys?
- Python - Convert given list into nested list
- Nested list comprehension in python
- How to copy a list to another list in Java?
- Flatten Nested List Iterator in Python
- Find maximum length sub-list in a nested list in Python
- How to copy or clone a C# list?
- How to copy a List collection to an array?

Advertisements