Open In App

Python – How to copy a nested list

Last Updated : 19 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a nested list we need to copy it. For example, we are given a nested list a = [[1, 2], [3, 4], [5, 6]] and we need to copy it so that output should be [[1, 2], [3, 4], [5, 6]].

Using a For Loop

To copy a nested list using a for loop, we iterate over each sublist and create a new list for each sublist to ensure nested structure is preserved. This creates a shallow copy where inner lists are copied but the inner elements are still references to the original ones.

Python
a = [[1, 2], [3, 4], [5, 6]]
b = []

for sublist in a:
    b.append(sublist[:])  # Copy each sublist

print(b)  

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

Explanation:

  • For loop iterates through each sublist in the original list “a” and uses sublist[:] to create a shallow copy of each sublist.
  • These shallow copies are appended to new list “b” resulting in a nested list “b” with same structure as a but independent sublists.

Using List Comprehension

Using list comprehension we can create a new list by iterating over each sublist in the original list and making a shallow copy of each sublist with sublist[:]. This results in a new nested list where the inner lists are independent of the original ones.

Python
a = [[1, 2], [3, 4], [5, 6]]  
# Create a new list where each sublist is shallow copied  
b = [sublist[:] for sublist in a]  

print(b)  

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

Explanation:

  • List comprehension iterates over each sublist in a and uses sublist[:] to make a shallow copy of each sublist.
  • Resulting list “b” contains independent copies of the sublists from a preserving original structure.

Using map with list()

Using map() with list() in Python applies a function to each item in an iterable and returns a new list.

Python
a = [[1, 2], [3, 4], [5, 6]]

# Copy using map and list()
c = list(map(list, a))

# Verify the copy
a[0][1] = 99
print("Original List:", a)
print("Copied List:", c)

Output
Original List: [[1, 99], [3, 4], [5, 6]]
Copied List: [[1, 2], [3, 4], [5, 6]]

Explanation:

  • c = list(map(list, a)) creates a shallow copy of each inner list in “a”, so “c” contains new lists with same values as “a”.
  • changing a[0][1] only affects “a” not “c” because the inner lists are independently copied.

Next Article
Practice Tags :

Similar Reads