What’s the difference between shallow copy and deep copy in Python? Give an example.
What’s the difference between shallow copy and deep copy in Python? Give an example.
310
21-Apr-2025
Updated on 30-Oct-2025
Mayank kumar Verma
27-Oct-2025Shallow copy ( Quick Duplication )
A shallow copy creates a new outer object but it copies the references (memory location ) of the inner, nested object.
Deep copy (full indenpendence )
a deep copy creates a new outer object and recursively creates a new copies of all nested objects inside of it.
Simple Example
Imagine
original = [[1], [2]].[[1], [2]][[1], [2]][[1], [2]]original[0][0] = 999[[999], [2]][[999], [2]][[1], [2]][1]with the original, so the change is seen in both.Use
copy.copy()for shallow, andcopy.deepcopy()for deep.Khushi Singh
24-Apr-2025Understanding the difference between shallow and deep copy represents an essential aspect of working with nested lists or dictionaries in the Python programming language. These two types of copying methods create duplicates of objects yet they function in completely different ways regarding nested elements. During a shallow copy operation a single new object emerges yet the original contains entire nested objects which the new object fails to duplicate. The shallow copy process duplicates only the object references but it does not duplicate those nested objects.
The original object along with its shallow copy will share identical references to their mutable types as dictionaries and lists. When using a shallow copy the modifications that occur to the nested objects present in the original object will also affect those nested objects. Deep copies generate an independent object duplicate together with independent instances for all original object nestings.
The recursive element copy process creates a stand-alone duplicated object that disconnects it from its original version. A deep copy of data preserves the original object state since it does not apply alterations made to the nested details. The Python copy module includes two functions: copy() for shallow copying and deepcopy() for deep copying.
Programmers must use deep copy functions when dealing with data because unintended changes in machine learning models can impact their results or behavior.
A shallow copy will maintain identical nested elements whereas deep copy produces independent duplicate versions.