{"id":80211,"date":"2021-02-26T09:00:21","date_gmt":"2021-02-26T03:30:21","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=80211"},"modified":"2021-02-26T09:00:21","modified_gmt":"2021-02-26T03:30:21","slug":"python-deep-shallow-copy","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/","title":{"rendered":"Python Deep Copy and Shallow Copy with Examples"},"content":{"rendered":"<p>Do you ever wonder how one can simply fill data once and then merely make its copy to prefer ease? Not possible for a textbook, of course, but Python has its own magic, and yes, it does this for his coder.<\/p>\n<p>How?<\/p>\n<p>Copies in python are such functions that maintain a skeleton of any code as a carbon copy in the library. This helps the coder to retrieve any such code in case of any error.<\/p>\n<p>There are basically two types of copies: shallow copy and deep copy. But there lies a major difference in the working of both, what is it and where are they used?<\/p>\n<p>Everything is explained in the article. So, let&#8217;s get started.<\/p>\n<h2><span style=\"font-size: 16px\">Python Copy Module<\/span><\/h2>\n<p>A copy module is used when some changes are needed in the backup files but not in the main source code. This refers to the internal storage that can be manipulated from the coder\u2019s point of view but not the user\u2019s point of view in the main source file.<\/p>\n<p>Some of the attributes are:<\/p>\n<p><strong>1. copy.copy(x)<\/strong><br \/>\nIt returns a shallow copy of x.<\/p>\n<p><strong>2. copy.deepcopy(x)<\/strong><br \/>\nIt returns a deep copy of x.<\/p>\n<p><strong>3. exception copy.error<\/strong><br \/>\nIt returns an exception if needed.<\/p>\n<p>A shallow copy creates a separate file within the text file which stores information. The original code is never manipulated, but changes can be surely made in the new copied file.<\/p>\n<p>The basic idea of shallow and deep copy constructs a few debugging problems within the text.<\/p>\n<p>Recursive objects face problems in shallow copy, but this is resolved with deep copy. This also intends the deep copy to work more efficiently than the shallow copies in runtime.<\/p>\n<p>This module copies functions and classes both deep and shallow by returning the original object unchanged in the main code itself.<\/p>\n<p>It is generally also compatible with the way these are treated by the pickle module in any code specific run time in python.<\/p>\n<h3>How to Perform Shallow and Deep Copy in Python?<\/h3>\n<p><strong>Shallow Copy Syntax in Python:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import copy\ncopy.copy(objectvariable_name)\n<\/pre>\n<p><strong>Deep Copy Syntax in Python:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import copy\ncopy.deepcopy(objectvariable_name)\n<\/pre>\n<p><strong>Python Copy Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#method to print the list\nthisistech= [1, 2, 3],['#',\"*\",\"-\"]\nnewtech=[0,9,8,7]\n#the functions returns as it is \nprint('Old List:', thisistech)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Old List: ([1, 2, 3], [&#8216;#&#8217;, &#8216;*&#8217;, &#8216;-&#8216;])<\/div>\n<h2>Python Deep Copy<\/h2>\n<p>While a deep copy in Python creates a new object, it also inserts the new object in the original object by efficiently copying it. Similarly it copies an object into another object within the main code. This basically signifies that the required changes in the main dictionary are well automated in the main library also.<\/p>\n<p><strong>Python Deep Copy Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&gt;&gt;&gt; import copy\n&gt;&gt;&gt; list1=[1,0,[7,9],6]\n&gt;&gt;&gt; list2=copy.deepcopy(list1) #Making a deep copy\n&gt;&gt;&gt;print( list1)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">[1, 0, [7, 9], 6]<\/div>\n<p><strong>Addition of Nested Loop:<\/strong> Nested loop, unlike in lists, can be added in the deep copy. The shallow copy doesn\u2019t support the reframe work of nested loops in new versions of python. Though it can be used in the old versions.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">l=int(input(\"enter number\"))\n \n \nold__list = [[1, 1, 1], [2, 2, 2], [5, 5, 5]]\n \nprint(\"Old list:\", old__list)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">enter number 67<br \/>\nOld list: [[1, 1, 1], [2, 2, 2], [5, 5, 5]]<\/div>\n<h3>Issues With Python Deep Copy<\/h3>\n<p>While it is possible that recursive objects cause a recursive loop; these are the compound objects that directly or indirectly reference themselves. And it is possible that a deep copy may copy too much.<br \/>\nTo deal with these problems, deepcopy() also :<\/p>\n<p>1. Deep copy parses the newly added information in its file. This helps the coder to identify new files easily in the code.<br \/>\n2. Deep copy does not allow the coder to overwrite in the code, but builds a copy of the shallow code using internal files.<br \/>\n3. Deep copy, as well as shallow copy, is made by parsing a list or tuple together in the runtime.<\/p>\n<p>Regardless of this, the copy module uses the registered pickle functions from the copyreg module within the code itself, it does not refer to the original code.<\/p>\n<p><strong>Copying Arbitrary Python Objects:<\/strong> Python arbitrary objects can be compiled in a list easily. It can be done by adding the elements recursively in the runtime for any defined list.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Point:\n    def __init__(self, A, B):\n        self.P = A\n        self.Q= B\n\n\nA = int(input(\"a\")\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">&gt;&gt;&gt; a<\/div>\n<h2>Python Shallow Copy<\/h2>\n<p>While using a Shallow Copy in Python, the coder creates a new object in which he\/she recursively puts all the copies of objects into the original code. Similarly, we copy a reference of an object into another object also. Any changes the coder makes to the copy do reflect in the original copy of code in the runtime.<\/p>\n<p><strong>Python Shallow Copy Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&gt;&gt;&gt;import copy\nlist=1,0,[7,9],6\nlist_2=copy.copy(list) #Making a shallow copy\nprint(list)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">(1, 0, [7, 9], 6)<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>Shallow Copying Dictionaries:<\/strong> This is a general method for providing an interface in the main source code.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&gt;&gt;&gt; dict_1={'a':0,'b':2,'c':[0,2,3]}\n \n \ndict_2=dict_1.copy()\n \ndict_2['c'].append(9)\ndict_1={\"a\": 0}\nprint(dict_2)\n \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">{&#8216;a&#8217;: 0, &#8216;b&#8217;: 2, &#8216;c&#8217;: [0, 2, 3, 9]}<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>Adding any element as [0,0] to the list, using shallow copy:<\/strong> This method adds elements by extracting from one list to another one by one.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import copy\nold_list0 = [[1,1], [2,2]]\nnew_list1 = copy.copy(old_list0)\nold_list0.append([0,0])\nprint(\"New list:\", new_list1)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">New list: [[1,1], [2, 2,]]<\/div>\n<p><strong>Adding new nested objects using Shallow copy:<\/strong> The objects are oriented from the list, and then extracted in the copies of the source code.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import copy\nl=(\u201center number\u201d)\nli=[]\nl.append(li)\nprint(li)\nlistone = [[1, 1, 1], [2, 2]]\nn=(\u201center number\u201d)\nni=[]\nn.append(ni)\nprint(ni)\nnew_list = copy.copy(old_list)\noldlist0[1][1] = 'pq'\nprint(\"New list:\", new_list1)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Error<\/div>\n<p>#no new obj to append<\/p>\n<h3>Difference Between Python Deep Copy and Shallow Copy<\/h3>\n<p>Having discussed what shallow and deep copies are and why we create copies, it&#8217;s time to learn about the difference between them. Actually, there are just two core differences and they&#8217;re linked with each other:<\/p>\n<ol>\n<li>Deep copy stores copies of an absolute object&#8217;s values, whereas a shallow copy stores references which are absolute to the original memory address in the runtime code.<\/li>\n<li>Deep copy doesn&#8217;t reflect any change made to the new\/copied object in the original object; but shallow copy does the same in the run time code.<\/li>\n<\/ol>\n<h4>Example for Python Deep Copy vs Shallow Copy<\/h4>\n<p><strong>Code 1:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import copy\nresult_p = [100,90], [30,40] \nresult_q = [10,90], [340] \n \n \nprint(\"Original List: \")\nprint(result_p)\nprint(\"Deep Copy:\")\nprint(result_q)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Original List:<br \/>\n([100, 90], [30, 40])<br \/>\nDeep Copy:<br \/>\n([10, 90], [340])<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>Code 2:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import copy\nresult_p = [[85, 82], [ 88, 90]] \n \n \nprint(\"Original List: \")\nprint(result_p)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Original List:<br \/>\n[[85, 82], [88, 90]]<br \/>\n&gt;&gt;&gt;<\/div>\n<h2>Conclusion<\/h2>\n<p>As the article concludes, we get to know about the 2 different types of copies that python serves us and their correct usage. Copying is easy, but the assessment of where to do it is a tough task.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Do you ever wonder how one can simply fill data once and then merely make its copy to prefer ease? Not possible for a textbook, of course, but Python has its own magic, and&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":80231,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[3371,3372,3373,3374],"class_list":["post-80211","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python-copies","tag-python-deep-copy","tag-python-deep-copy-vs-shallow-copy","tag-python-shallow-copy"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Deep Copy and Shallow Copy with Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn Python deep &amp; Shallow copy. Deep copy makes copying process recursive. Shallow copy creates new object which stores reference of original elements\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Deep Copy and Shallow Copy with Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn Python deep &amp; Shallow copy. Deep copy makes copying process recursive. Shallow copy creates new object which stores reference of original elements\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-02-26T03:30:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Shallow-Copy-Deep-Copy.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Deep Copy and Shallow Copy with Examples - TechVidvan","description":"Learn Python deep & Shallow copy. Deep copy makes copying process recursive. Shallow copy creates new object which stores reference of original elements","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/","og_locale":"en_US","og_type":"article","og_title":"Python Deep Copy and Shallow Copy with Examples - TechVidvan","og_description":"Learn Python deep & Shallow copy. Deep copy makes copying process recursive. Shallow copy creates new object which stores reference of original elements","og_url":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-02-26T03:30:21+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Shallow-Copy-Deep-Copy.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Deep Copy and Shallow Copy with Examples","datePublished":"2021-02-26T03:30:21+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/"},"wordCount":963,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Shallow-Copy-Deep-Copy.jpg","keywords":["Python COpies","python deep copy","Python deep copy vs shallow copy","Python Shallow Copy"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/","url":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/","name":"Python Deep Copy and Shallow Copy with Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Shallow-Copy-Deep-Copy.jpg","datePublished":"2021-02-26T03:30:21+00:00","description":"Learn Python deep & Shallow copy. Deep copy makes copying process recursive. Shallow copy creates new object which stores reference of original elements","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Shallow-Copy-Deep-Copy.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Shallow-Copy-Deep-Copy.jpg","width":1200,"height":628,"caption":"Python deep copy and shallow copy"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-deep-shallow-copy\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Deep Copy and Shallow Copy with Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80211","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=80211"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80211\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/80231"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=80211"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=80211"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=80211"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}