Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3601152
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T20:35:08+00:00 2026-05-18T20:35:08+00:00

I am trying to understand the difference between shallow copy and deep copy in

  • 0

I am trying to understand the difference between shallow copy and deep copy in python. I read many posts here and they have been helpful. However, I still don’t understand the difference well. Can someone please explain the reason for the result below. The result that I do not understand is indicated in the comments.

Thanks very much.

import copy
import random

class understand_copy(object):
    def __init__(self):
        self.listofvalues = [4, 5]

    def set_listofvalues(self, pos, value):
        self.listofvalues[pos] = value

ins = understand_copy()

newins = copy.copy(ins)

newins.set_listofvalues(1,3)
print "ins = ", ins.listofvalues
print "in newins", newins.listofvalues
# Gives the following output as I would expect based on the explanations.
# prints ins = [4, 3]
# prints newins = [4, 3]


newins.listofvalues.append(5)
print "ins =", ins.listofvalues
print "newins =", newins.listofvalues
# Gives the following output as I would expect based on the explanations.
# prints ins = [4, 3, 5]
# prints newins = [4, 3, 5]


newins.listofvalues = [10, 11]
print "ins = ", ins.listofvalues
print "newins = ", newins.listofvalues
# Gives
# ins = [4, 3, 5]
# newins = [10, 11]
# This is the output that I do not understand. 
# Why does ins.listofvalues not change this case.**
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T20:35:09+00:00Added an answer on May 18, 2026 at 8:35 pm

    In Python, object’s field keep reference to object. So when you assign the new list in your exemple, you’re changing the object that is referenced by the field, not its content. Before the affectation, the listofvalues property of both object where referencing the same list, but after the affectation, they are referencing two different list.

    This is equivalent to the following code :

    >>> a = [4, 5]
    >>> b = a
    >>> b.append(3)
    >>> b
    [4, 5, 3]
    >>> a
    [4, 5, 3]
    >>> b = [6, 7]
    >>> b
    [6, 7]
    >>> a
    [4, 5, 3]
    

    If you wanted to change the content of the list, and not the reference, you need to use slicing. That is :

    >>> a = [4, 5, 3]
    >>> b = a
    >>> b[:] = [6, 7]
    >>> b
    [6, 7]
    >>> a
    [6, 7]
    

    NOTE: the following is based on my understanding of the internals of Python 2.6. It is thus really implementation specific, however the mental model it gives you is probably pretty close of how the language rule are written and should work with any implementation.

    In Python, objects are always accessed through references (as in Java, not C++). However, a variable name or attribute name can be though as a binding in a dictionary, and are implemented as such in CPython (except for the local variable optimization, the presence of __slots__, or the pseudo-attributes exposed via __getattr__ and friends).

    In Python, each object as a private dictionary mapping each of its attribute name to the value. And the interpreter has two private dictionary holding the mapping between local and global variable name to their value. When you change the value of a variable or attribute of an object, you are just changing the binding in the corresponding dictionary.

    So in you example, you have the same behavior as in the following code:

    def understand_copy():
       return {'listofvalues': [4, 5]}
    
    def deepcopy(obj):
       if instance(obj, dict):
           copy = {}
           for key, value in obj.iteritems():
               copy[key] = deepcopy(value)  # Note the recursion
           return copy
       if instance(obj, list):
           copy = []
           for value in obj:
               copy.append(deepcopy(value)) # Note the recursion
           return copy
       return obj
    
    def copy(obj):
       if instance(obj, dict):
           copy = {}
           for key, value in obj.iteritems():
               copy[key] = value  # No recursion this time, the copy is shallow
           return copy
       if instance(obj, list):
           copy = []
           for value in obj:
               copy.append(value) # No recursion this time, the copy is shallow
           return copy
       return obj
    
    globals = {}
    globals['ins'] = understand_copy()
    globals['new'] = copy(global['ins'])
    # Now globals['ins']['listofvalues']
    # and globals['new']['listofvalues']
    # reference the same object!
    
    globals['ins']['listofvalues'].__setitem__(0, 3)
    globals['ins']['listofvalues'].append(5)
    # We are calling function on one object,
    # but not changing a binding, so the two
    # 'listofvalues' attribute still refers
    # to the same object.
    
    globals['ins']['listofvalues'] = [10, 11]
    # Now we changed the binding of the name
    # in the dictionary 'ins' so now the two
    # objects attributes points to different
    # lists.
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand the difference between mysqli's query() and prepare(). I have
I am trying to understand the object size difference between 32 bit and 64
I'm trying to sort the difference between Sound.readData and Sound.lock in the FMOD library
In Java, is null an existing object on the heap? I'm trying to understand
Trying to understand What is IConnectionPoint and how this is connected to IConnectionPointContainer,IEnumConnectionPoints,IEnumConnections and
I am trying to understand the purpose of the synthesize directive with property name
I am new to Spring Framework and trying to understand the functionality of formBackingObject
can somebody please explain, what exactly does it mean? I'm trying to understand what
I am trying to interface to Ada in C++ using externs. What is the
Unfortunately the names of these methods make terrible search terms, and I've been unable

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.