Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

Shallow Copy and Deep Copy in Python

Shallow Copy and Deep Copy in Python

In this section, we will learn about the Shallow Copy and Deep Copy in the Python program. But before going through the topic, we need to understand how the copy works in Python.

Shallow Copy and Deep Copy in Python

Like other programming languages, the assignment operator (=) in Python is used to copy or assign one variable to another. When we use the assignment (=) symbol to assign values, the assignment operator does not copy the actual values of the first variable. Instead, it passes the reference address of the original variable or object assigned by another variable in the program. Therefore we can say it does not create a new data copy for a new object/variable; instead, they provide the same address for copying elements that are referenced by old variables or objects.

Let’s create a program to copy or assign the first variable’s value to another variable in Python.

Copy.py

 first_var = "Welcome to the JavaTpoint."
sec_var = first_var # assign the first_var to the sec_var for referencing the address.
print(" ID/ Address of the first variable is: ",  id(first_var) )
print(" The value of the first variable: " + first_var)
print(" ID/ Referencing address of the second variable is: ", id(sec_var) ) # print the referencing address of the first variable
print(" The value of the Second variable: " + sec_var) 

Output

 ID/ Address of the first variable is:  1970811644864
 The value of the first variable: Welcome to the JavaTpoint.
 ID/ Referencing address of the second variable is:  1970811644864
The value of the Second variable: Welcome to the JavaTpoint.     

In the above example, the same string or Id is referenced by the Second variables. Therefore, we can say that an assignment operator (=) does not create a separate copy for a new variable. Instead, it passes the reference address of the old variable to get the same value in programming.    

Copy Module

Python Copy Module is an inbuilt function that keeps the original values unchanged and performs modification only in copied variables or vice versa. We can perform the copy operation in the following ways:

  1. Deep Copy
  2. Shallow Copy

The Copy Module is used in Shallow Copy and Deep Copy operations of Python. Let’s understand these topics with an example.

What is the Python Deep Copy?

Python Deep Copy is a recursive process for copying the items of the object. It is used to create a copy for a new object that stores or copies references of old objects or variables to access original values. In other words, it creates a separate copy for the new object that recursively adds the copies of items or values presented in the original list. If we made any changes to the copy object, it does not reflect any change in the original objects.

Syntax

copy.deepcopy(x)

A deepcopy(x) function available in the copy module to perform the copy operation. To use the deepcopy() function, we need to import the copy module in the Python program. A deepcopy() function contains an x parameter that holds the reference of the original object.

Shallow Copy and Deep Copy in Python

Let’s create a program to demonstrate the deepcopy() function in Python.

Copydeep.py

 # import the copy module to use the deepcopy() function
import copy
# initialize the elements of List1
lt1 = [4, 5, [1, 7], 8]
# Use deepcopy() function to perform the Deep Copy
lt2 = copy.deepcopy (lt1) # pass the reference of the List1 in deepcopy() function
# Display the original elements of the list 1
print (" Display the original list before using the Deep Copying ")
for i in range (0, len(lt1)):
    print (lt1 [i], end = " ")
print( "\r")
# Display the copied elements in List2
print ("Display the copied elements in List2", lt2)
# Update the List2 index at lt2[2][0] position
lt2[2] [0] = 7
# Display the changes into the list lt2
print (" Display the modification in copied list (lt2) ")
for i in range(0, len (lt1)):
    print (lt2 [i], end = " ")
# ir does not affect the original list
print ("\n Display the original list (lt1) after modification in List2 ")
for i in range (0, len(lt1)):
    print (lt1[i], end = " ") 

Output

 Display the original List before using the Deep Copying
4 5 [1, 7] 8
Display the copied elements in List2 [4, 5, [1, 7], 8]
 Display the modification in copied list (lt2)
4 5 [7, 7] 8
 Display the original list (lt1) after modification in List2
4 5 [1, 7] 8 

In the above program, we use the deepcopy() function to create a separate copy of the original list/ object as lt2. If we made any changes to the copied object (lt2), it does not reflect any modification to the original object (lt1).

Update the nested object using the deepcopy() function

Deepcopy2.py

 import copy
lt1 = [ [5, 5, 5 ], [4, 4, 4], [10, 10, 10] ]
# use deepcopy() function to pass the reference of the lt1 object.
new_lt = copy.deepcopy(lt1)
# display the original elements of the list 1
print (" Display the original list before performing the Deep Copying ")
for i in range (0, len(lt1)):
    print (lt1 [i], end = " ")
print( "\r")
print(" Display the copied elements of the New List", new_lt)
lt1[0][2] = 'AA' # pass the modifying parameter at the location [0][2]
print("Display the updated old list (lt1)", lt1) # print the updated old list
print("Display the copied list (new_lt)", new_lt) # print the new list 

Output

 Display the original list before performing the Deep Copying
[5, 5, 5] [4, 4, 4] [10, 10, 10]
 Display the copied elements of the New List [[5, 5, 5], [4, 4, 4], [10, 10, 10]]
Display the updated old list (lt1) [[5, 5, 'AA'], [4, 4, 4], [10, 10, 10]]
Display the copied list (new_lt) [[5, 5, 5], [4, 4, 4], [10, 10, 10]] 

What is the Shallow Copy in Python?

A Shallow Copy is similar to the Deep Copy for creating the copy of new variables/objects. It contains the same reference address for new objects that pointing the original object’s values. It does not create a separate copy for a new object or copied object in memory. Suppose we made any changes to the copied object; it will reflect the changes on the original object’s values because both variables are pointing to the same address in the computer memory. Hence, we can say it works like the normal copy function in Python

Syntax

copy. copy(x)

A copy() function available in the copy module, and to use the Shallow Copy operation, we need to import the copy module in the Python program. A copy() function contains an x parameter that holds the reference of the original object.

Shallow Copy and Deep Copy in Python

Let’s create a program to demonstrate the Shallow Copy in Python.

shallow.py

 # import the copy module to use the copy() function
import copy
# initialize the list 1 elements in Python
lt1 = [4, 5, [1, 7], 8]
# Use copy() function to perform the shallow copy
lt2 = copy.copy (lt1) # pass the list 1 in copy() function
# Display the original elements of the list 1
print (" Display the original lists before performing the Shallow Copying ")
for i in range (0, len(lt1)):
    print (lt1 [i], end = " ")
print("\n Display the copied elements of the list ", lt2)
# update the copied elements at position lt2[2][0]
lt2[2] [0] = 7
# Display the changes into the list lt2
print (" Display the changes in the copied list after using the Shallow Copying ")
for i in range(0, len (lt1)):
    print (lt2 [i], end = " ")
# Display the changes not affected in the original list
print ("\n Display the original elements list (lt1) after changing the copied list's elements (lt2) ")
for i in range (0, len(lt1)):
    print (lt1[i], end = " ") 

Output

 Display the original lists before performing the Shallow Copying
4 5 [1, 7] 8
 Display the copied elements of the list  [4, 5, [1, 7], 8]
 Display the changes in the copied list after using the Shallow Copying
4 5 [7, 7] 8
 Display the original elements list (lt1) after changing the copied list's elements (lt2)
4 5 [7, 7] 8 

In the above program, we use the copy() function to copy the new object/ list as lt2. Now lt2 stores the same content or data that the original object or list lt1 occupies. And when we perform some changes to the copied object lt2, it displays the changes in both the copied and original object of the list because both objects point to the same address in memory.

Add nested object using the copy() function

nestedCopy.py

 # write a program to add [8, 8, 8] items to an old list using the Shallow Copy in Python.
import copy # import the copy module in Python
old_lt = [ [1, 1, 1], [2, 2, 2], [3, 3, 3] ]
print (" Display the old list before adding the new items in list 1", old_lt)
new_lt = copy.copy (old_lt) # use copy() function to copy the reference of the old_lt
print (" Display the copied list ", new_lt)
old_lt.append( [8, 8, 8]) # add the items into the old list
# print the old and new list after adding the items.
print ("Display the old list after adding the elements ", old_lt)
print ("Display the copied list after adding the element into the list 1", new_lt) 

Output

 Display the old list before adding the new items in list 1 [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
Display the copied list  [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
Display the old list after adding the elements  [[1, 1, 1], [2, 2, 2], [3, 3, 3], [8, 8, 8]]
Display the copied list after adding the element into the list 1 [[1, 1, 1], [2, 2, 2], [3, 3, 3]] 



ADVERTISEMENT
ADVERTISEMENT