Skip to content
  • Recent
  • Categories
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (Yeti)
  • No Skin
Collapse

FastQA

  1. Home
  2. Categories
  3. Interview Questions
  4. What is difference between copy() and deepcopy() in Python

What is difference between copy() and deepcopy() in Python

Scheduled Pinned Locked Moved Interview Questions
python developerbackend engineer
1 Posts 1 Posters 23 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • fastqaF Offline
    fastqaF Offline
    fastqa
    wrote on last edited by fastqa
    #1

    In Python, copy and deepcopy come from the copy module and are used to duplicate objects.

    The key difference lies in how they handle nested objects.

    1. Shallow Copy (copy.copy())

    Creates a new object but does not recursively copy nested objects (like lists or dicts inside the object).

    If the original object contains mutable objects (lists, dicts, etc.), modifications to those mutables in the copied object will affect the original.

    import copy
    
    original = [1, [2, 3], 4]
    shallow_copy = copy.copy(original)
    
    shallow_copy[1][0] = 99  # Modifies the nested list
    print(original)  # Output: [1, [99, 3], 4]
    

    Explanation: Since copy.copy() only creates a new top-level object but keeps references to inner objects, changes in the nested list shallow_copy[1] reflect in the original.

    2. Deep Copy (copy.deepcopy())

    Creates a new object and recursively copies all nested objects.
    Modifications in the copied object will not affect the original.

    deep_copy = copy.deepcopy(original)
    
    deep_copy[1][0] = 42
    print(original)  # Output: [1, [99, 3], 4] (unchanged)
    

    Explanation: deepcopy() creates an entirely independent copy of the object, including all nested elements.

    3. When to Use?

    Use copy.copy() when your object only contains immutable elements (like numbers, strings, tuples) or when shallow copying is sufficient.

    Use copy.deepcopy() when your object contains nested mutable objects and you want a fully independent copy.

    1 Reply Last reply
    1
    Reply
    • Reply as topic
    Log in to reply
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes


    • Login

    • Don't have an account? Register

    • Login or register to search.
    • First post
      Last post
    0
    • Recent
    • Categories
    • Tags
    • Popular
    • World
    • Users
    • Groups