Hello, I want to duplicate a list in python. The way I want is, I need two list with same content pointing to different memory Location. What I tried is

Dup_List = Original_List[:]

, but lookes like even this is making both list point to same memory location.

Both the List are 2D

Thanks in advance

Dani AI

Generated

Short answer: slicing or calling list() / copy() on a 2D list only makes a new outer list; the inner lists remain the same objects. That explains the behavior seen by . is correct that a true independent duplicate of nested lists requires a deep copy, and ’s id check already shows the outer lists are distinct while their elements can still be shared.

Example that demonstrates the shallow-copy problem:

a = [[1, 2], [3, 4]]
b = a.copy()          # shallow copy of the outer list
b[0][0] = 99
print(a)              # outer list a is modified: [[99, 2], [3, 4]]

Proper deep copy using the standard library:

from copy import deepcopy
a = [[1, 2], [3, 4]]
b = deepcopy(a)
b[0][0] = 99
print(a)              # a remains [[1, 2], [3, 4]]

A faster alternative when working with a true 2D list of primitives (no deeper nesting) is to copy the inner rows individually rather than deep-copying every level:

b = [list(row) for row in a]   # creates new inner lists too

Troubleshooting notes: verify independence with id(a) and id(a[i]) to confirm which level is shared. deepcopy handles circular references and arbitrary nesting but can be significantly slower and may duplicate complex objects in unwanted ways; when performance matters and the structure is only two levels deep, the list-comprehension approach is usually best. For large numeric matrices, consider using arrays (NumPy) and their copy methods instead of nested Python lists.

Recommended Answers

All 2 Replies

mylist1 = [1, 2, 3]

mylist2 = mylist1[:]

print(id(mylist1))
print(id(mylist2))

''' result show 2 different memory locations ...
42368056
34857768
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.