Shallow Copy Vs Deep Copy in Python

Krish Naik · Intermediate ·🏗️ Systems Design & Architecture ·5y ago

Key Takeaways

Explains the difference between shallow copy and deep copy in Python

Full Transcript

hello all my name is krishnak and welcome to my youtube channel so guys we are going to continue the advanced series of python and here we are going to see the exact difference between shallow copy versus deep copy so in this particular video i'm going to take three things that we are going to learn one is equal to then one is copy operation and then one is something called as deep copy operation so we'll try to understand this particular difference i had a lot of confusion before on this but i try to learn it i try to understand it and there were some of the queries that were asked by some of the people in one of my classes at that time i just tried to dig dive into it and try to understand the entire concept and the same concept i'm going to explain it over here to you all now remember whenever you want to learn about shallow copy or deep copy always consider the data that you are going to or the variables that you are going to initialize should be collection because collections of elements are mutable and they should also have this mutability property itself right and if you don't know about mutability don't worry i'll also be uploading a video very soon about that also now let's take one example and let's understand first going i will go ahead and understand about this equal to operation now suppose if i want to apply a list one i will create a list one considering some elements like list one is equal to one two three four and then i will also create another list which will be assigned to list one now this equal to operation i'm talking about this list2 is basically assigned with list one now once i execute this here you will be able to see this is my list one and then you'll also be able to see this is my list two okay so list one is this list two is this now what happens suppose i try to uh take out one element of list two suppose i want to take out the index element of list two and when i check the index one i'm getting the value as two suppose i assign it with some other value like one okay and i execute it now what will happen is that i will be able to see that in list two i'll be getting that particular element in the second in the first index as thousand now one important thing that you have to note that even though i check the element of list one here also it has got updated now why probably this thing may have happened because understand list one when it is creating this collection of items it has been creating in some memory location and both the variables are actually referring that but same memory location so that is the reason if one of the variable changes the element it will also get reflected in the memory itself so both the variable will be referring to the same memory itself right so this is the most important thing and this is what you have understood about equal to before going ahead with respect to this particular video this video has been sponsored by an academy so guys if you are in the final year of a graduation or planning to prepare for gate or eac examination then you are at the right place and academy is back with its cs or it batch evolve 2022 these batches are starting from 18 jan 2021 don't miss a single class take all the live session and prepare with the best unacademy educators including ravindra babu rahula if you don't know about ravindra babu ravula guys he's an amazing teacher and you can also see his youtube videos with respect to gate you will be getting 800 plus hours of total lectures covering the full gate or ac course along with solving all your doubts do make sure that you try to use uh my code that is kn06 to get an additional 10 percent discount you can also take the demo class to get a full clarity about the educator that is ravindra babu ravula and subscribe to this particular platform all the information regarding this will be given in the description of this particular video now what we will do is that we will try to use again we will just copy this and we'll go with our copy operation now see this i'm just going to say copy operation now inside this copy operation what i'm going to do instead of just assigning like list one i will do dot copy operation okay i'll do something called as dot copy okay now when i do dot copy that basically means it says that okay i'm going to take all the elements of list one and remember guys this is a kind of shallow copy okay this is a kind of shallow copy i'll tell you the exact difference between shallow and deep copy but just understand when we are taking this shallow copy as an example we have to use dot copy operation now when we do use dot copy operation you here you will be able to see once i'll execute it okay suppose this is my list 2 and if i try to see this particular elements and suppose i want to assign i want to change any elements over here suppose i want to change the first index element right so what is my first index element 2 let me just consider that i want to make it to thousand now when i do this particular operation remember when i do dot copy operation here it is going to make a different memory location it is not going to just refer the same memory location okay now if i go and see my list two and if i try to compare with list one you'll be seeing that sorry it should be lst one you'll be seeing that in list two only your first index has been changed but in list one it has not been changed because now both are having different different memory location now this is one thing this is one very very important thing now guys if i create some list or i can say if i create some nested list this shallow copy definition whatever we did over here will change a little bit let me just show you an example again i'm going to take a shallow copy with respect to nested list okay this will be with respect to nested list and suppose let me consider and create some nested sub list okay so something like this 5 6 7 8 and then i will just create this and now if i go and see this here you is your list one so this is basically your list one and here you can actually see your list two right so i have my list one and list two now just consider over here one very very important thing definitely whenever i use nested sub list okay over here initially i just created this list right it was a single dimension list i can consider in that way i did not had a nested list over here but here when i created this nested list sub nested list or nested list at that time you'll be able to see that if i try to change one element like this suppose if i say list of one list of one is nothing but this one and suppose if i go and see zero this basically referring to the five element if i try to see this value i'm getting five now if i try to replace this with something else like hundred okay because here you'll be able to understand the exact difference between shallow copy and deep copy now if i go and see my list 2 here you'll be able to see that 100 is getting replaced 100 is getting assigned if i also go and see my list 1 here also you'll be able to see 100 is getting a sign now what is happening over here initially when you used like this in this particular way when i was trying to change only one single element inside a list that is basically an item right this is one item this is the other item this is the next item and this is the next item here we have this i can consider as one item right and this i can consider my next item inside this item you have different different objects right when you have in this particular scenario and when you try to change this particular value this value will get copied in both the list after you make the changes because it is referring to the same object inside the nested list both the variables are referring to the same object that is present inside the list this is the most important thing to understand okay in this scenario whenever you have a nested list and when you try to perform the same operation like how we did with respect to one specific element inside this nested list at that time those updation will happen if i take one more example suppose this is my list one right the if i'd write dot append when i do a dot append operation see this this is very very important in shallow copy if i do a dot append operation with some of the elements like 2 comma 3 comma 4 comma 5 and if i execute it now if i go and see my list 1 here you'll be able to see that i'm getting this particular element but since i've used this shallow copy over here if i go and see in list 2 here you will not be seeing that this value is getting appended so this item will not get copied but if you are making changes inside and um suppose if you are changing if you are if you are making changes on the object that is present inside the list at that time it will definitely make a change understand guys very very simple is that when i'm creating a nested list this is considered as a collection of item okay inside this i have various objects right one two three four right this will be getting referred by both list one and list two but when we have multiple items like this and when i'm adding suppose one item like two three four five at that time the same thing is not getting referred over here this is about shallow copy i'll talk about deep copy also now let's go ahead with respect to deep copy now in deep copy you try to do anything and for using deep copy i have to use import copy and inside this import copy what i'm going to do is that i'm going to first of all create a list one suppose this is my list one one comma two comma three comma four okay and list two is basically i'll just assign it to um i can use this copy library i'll say copy dot there's something called as deep copy and here i'm going to use list one now when i execute this okay suppose this is my list two and i want to change probably the first index element is equal to thousand here you will be able to always equal to 100 and now if you go and see your list two here you are getting hundred but when i go and see list one i'm not getting any value this works exactly like uh shallow copy in this scenario when you have a single nest a single uh list itself a single dimension list where you don't have nested list right this is not a listed list whenever this scenario is there remember deep copy in this scenario in this scenario i'll just write down a comment in a single dimension list when when i say single dimension don't over complicate it things guys it is not a nested list i'm just saying that so i'll say that in a normal list okay shallow copy is equal to deep copy okay now let's try to understand what happens if i try to make a nested list suppose this is my list one and here i'm going to take elements like this okay and here i'm going to say 1 2 3 or comma 3 comma 4 comma 5 and then i'll have one more list like 5 comma six comma seven okay now see this if i make list two and here i'll say that copy dot deep copy dot deep copy copy dot deep copy this is very very important to understand you'll face some kind of confusion i'd suggest go and just practice this here you'll be able to understand now see this this is my list 2 okay this is my list 2 right now when i am using list2 suppose i want to change one element one of zero at that time if i go and see this i'm getting three suppose if i change this element to hundred okay this is the element guys okay now if i go and see my lst2 and if i go and see my lst1 here you'll be able to see that now this copy is not being this value is not getting copied in the other list since we performed this only operation in list two this got only copied over here this is basically deep copy now for everything that we do a separate memory location is basically getting created this is the difference between shallow copy and deep copy guys in this case shallow copy is not equal to deep copy because it is creating a different memory location so i hope you understood this guys this is the basic difference understand if i try to perform with the help of shallow copy my shallow copy will be something like this see instead of using this deep copy i'll be using um i'll just say that list one dot copy so this is basically shallow copy okay and if i try to perform this operation again like this it will not work see here i'm getting 100 and if i go and see list one again i'm getting hundred but if i do with deep copy then here you'll be able to see that only list two element will get updated list one will not get updated so just try to have a look on to this particular notebook i've discussed three things equal to copy and deep copy operation and i hope you like this particular video please do subscribe the channel if you're not already subscribe i'll see you on the next video have a great day thank you and all bye

Original Description

guthub: https://github.com/krishnaik06/Machine-Learning-in-90-days/blob/master/Section%201-%20Python%20Crash%20Course/Shallow%20Copy%20Vs%20Deep%20Copy%20Python.ipynb Evolve for GATE 2022 | CS/IT: https://bit.ly/3svw5Cm Demo Class: CS/IT: https://unacademy.com/class/last-30-days-preparation-strategy-for-gate-2021-csit/R5NOYSA0 Use Code: KN06 ⭐ Kite is a free AI-powered coding assistant that will help you code faster and smarter. The Kite plugin integrates with all the top editors and IDEs to give you smart completions and documentation while you’re typing. I've been using Kite for a few months and I love it! https://www.kite.com/get-kite/?utm_medium=referral&utm_source=youtube&utm_campaign=krishnaik&utm_content=description-only All Playlist In My channel Interview Playlist: https://www.youtube.com/playlist?list=PLZoTAELRMXVM0zN0cgJrfT6TK2ypCpQdY Complete DL Playlist: https://www.youtube.com/watch?v=9jA0KjS7V_c&list=PLZoTAELRMXVPGU70ZGsckrMdr0FteeRUi Julia Playlist: https://www.youtube.com/watch?v=Bxp1YFA6M4s&list=PLZoTAELRMXVPJwtjTo2Y6LkuuYK0FT4Q- Complete ML Playlist :https://www.youtube.com/playlist?list=PLZoTAELRMXVPBTrWtJkn3wWQxZkmTXGwe Complete NLP Playlist:https://www.youtube.com/playlist?list=PLZoTAELRMXVMdJ5sqbCK2LiM0HhQVWNzm Docker End To End Implementation: https://www.youtube.com/playlist?list=PLZoTAELRMXVNKtpy0U_Mx9N26w8n0hIbs Live stream Playlist: https://www.youtube.com/playlist?list=PLZoTAELRMXVNxYFq_9MuiUdn2YnlFqmMK Machine Learning Pipelines: https://www.youtube.com/playlist?list=PLZoTAELRMXVNKtpy0U_Mx9N26w8n0hIbs Pytorch Playlist: https://www.youtube.com/playlist?list=PLZoTAELRMXVNxYFq_9MuiUdn2YnlFqmMK Feature Engineering :https://www.youtube.com/playlist?list=PLZoTAELRMXVPwYGE2PXD3x0bfKnR0cJjN Live Projects :https://www.youtube.com/playlist?list=PLZoTAELRMXVOFnfSwkB_uyr4FT-327noK Kaggle competition :https://www.youtube.com/playlist?list=PLZoTAELRMXVPiKOxbwaniXjHJ02bdkLWy Mongodb with Python :https://www.youtube.com/playlist?list=PLZoTA
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Krish Naik · Krish Naik · 0 of 60

← Previous Next →
1 Natural Language Processing|Stemming
Natural Language Processing|Stemming
Krish Naik
2 Natural Language Processing|BagofWords
Natural Language Processing|BagofWords
Krish Naik
3 Gaussian distribution or Normal Distribution in statisctics
Gaussian distribution or Normal Distribution in statisctics
Krish Naik
4 Natural Language Processing|TF-IDF for Machine Learning| Text Prerocessing
Natural Language Processing|TF-IDF for Machine Learning| Text Prerocessing
Krish Naik
5 Log Normal Distribution in Statistics
Log Normal Distribution in Statistics
Krish Naik
6 Covariance in Statistics
Covariance in Statistics
Krish Naik
7 Confusion matrix, Precision, Recall| Data Science Interview questions
Confusion matrix, Precision, Recall| Data Science Interview questions
Krish Naik
8 Tutorial 44-Balanced vs Imbalanced Dataset and how to handle Imbalanced Dataset
Tutorial 44-Balanced vs Imbalanced Dataset and how to handle Imbalanced Dataset
Krish Naik
9 Implementing a Spam classifier in python| Natural Language Processing
Implementing a Spam classifier in python| Natural Language Processing
Krish Naik
10 Tutorial 11-Exploratory Data Analysis(EDA) of Titanic dataset
Tutorial 11-Exploratory Data Analysis(EDA) of Titanic dataset
Krish Naik
11 Face Recognition using open CV and VGG 16 Transfer Learning
Face Recognition using open CV and VGG 16 Transfer Learning
Krish Naik
12 Pedestrian Detection using OpenCV from Videos
Pedestrian Detection using OpenCV from Videos
Krish Naik
13 Face and Eye Detection from Videos using HAAR Cascade Classifier
Face and Eye Detection from Videos using HAAR Cascade Classifier
Krish Naik
14 Reading, Writing and Displaying images with Opencv| OpenCV Tutorial
Reading, Writing and Displaying images with Opencv| OpenCV Tutorial
Krish Naik
15 OpenCV Installation | OpenCV tutorial
OpenCV Installation | OpenCV tutorial
Krish Naik
16 Face and Eye Detection from Images using HAAR Cascade Classifier
Face and Eye Detection from Images using HAAR Cascade Classifier
Krish Naik
17 Car Detection using HAAR Cascade and Opencv from Videos.
Car Detection using HAAR Cascade and Opencv from Videos.
Krish Naik
18 Using OpenFace for Face recognition in Keras
Using OpenFace for Face recognition in Keras
Krish Naik
19 OpenPose Tutorial with Tensorflow
OpenPose Tutorial with Tensorflow
Krish Naik
20 Multiple Linear Regression using python and sklearn
Multiple Linear Regression using python and sklearn
Krish Naik
21 Dimensional Reduction| Principal Component Analysis
Dimensional Reduction| Principal Component Analysis
Krish Naik
22 Movie Recommender System using Python
Movie Recommender System using Python
Krish Naik
23 TPR,FPR,FNR,TNR, Confusion Matrix
TPR,FPR,FNR,TNR, Confusion Matrix
Krish Naik
24 Precision, Recall and F1-Score
Precision, Recall and F1-Score
Krish Naik
25 Artificial Neural Network for Customer's Exit Prediction from Bank
Artificial Neural Network for Customer's Exit Prediction from Bank
Krish Naik
26 GridSearchCV- Select the best hyperparameter for any Classification Model
GridSearchCV- Select the best hyperparameter for any Classification Model
Krish Naik
27 RandomizedSearchCV- Select the best hyperparameter for any Classification Model
RandomizedSearchCV- Select the best hyperparameter for any Classification Model
Krish Naik
28 K Nearest Neighbor classification with Intuition and practical solution
K Nearest Neighbor classification with Intuition and practical solution
Krish Naik
29 K Means Clustering Intuition
K Means Clustering Intuition
Krish Naik
30 Create custom Alexa Skill- Lambda function- Part2
Create custom Alexa Skill- Lambda function- Part2
Krish Naik
31 Hierarchical Clustering intuition
Hierarchical Clustering intuition
Krish Naik
32 Implement Transfer Learning with a generic Code Template
Implement Transfer Learning with a generic Code Template
Krish Naik
33 Gender Classifier and Age Estimator using Resnet Convolution Neural Network
Gender Classifier and Age Estimator using Resnet Convolution Neural Network
Krish Naik
34 Unlock Your Application With Your Face using OpenCV
Unlock Your Application With Your Face using OpenCV
Krish Naik
35 Draw rectangle from webcam and sketch process it on a live feed
Draw rectangle from webcam and sketch process it on a live feed
Krish Naik
36 Complete Life Cycle of a Data Science Project
Complete Life Cycle of a Data Science Project
Krish Naik
37 How we can apply Machine Learning in Finance
How we can apply Machine Learning in Finance
Krish Naik
38 Deep Learning in Medical Science
Deep Learning in Medical Science
Krish Naik
39 How to switch your career to Data Science.
How to switch your career to Data Science.
Krish Naik
40 Linear Regression Mathematical Intuition
Linear Regression Mathematical Intuition
Krish Naik
41 Handle Categorical features using Python
Handle Categorical features using Python
Krish Naik
42 Machine Learning Algorithm- Which one to choose for your Problem?
Machine Learning Algorithm- Which one to choose for your Problem?
Krish Naik
43 DBSCAN Clustering Easily Explained with Implementation
DBSCAN Clustering Easily Explained with Implementation
Krish Naik
44 Curse of Dimensionality Easily explained| Machine Learning
Curse of Dimensionality Easily explained| Machine Learning
Krish Naik
45 Feature Selection Techniques Easily Explained | Machine Learning
Feature Selection Techniques Easily Explained | Machine Learning
Krish Naik
46 Tutorial 29-R square and Adjusted R square Clearly Explained| Machine Learning
Tutorial 29-R square and Adjusted R square Clearly Explained| Machine Learning
Krish Naik
47 Cross Validation using sklearn and python | Machine Learning
Cross Validation using sklearn and python | Machine Learning
Krish Naik
48 Handling Missing Data Easily Explained| Machine Learning
Handling Missing Data Easily Explained| Machine Learning
Krish Naik
49 Deploy Machine Learning Model using Flask
Deploy Machine Learning Model using Flask
Krish Naik
50 Deployment of Deep Learning Model using Flask
Deployment of Deep Learning Model using Flask
Krish Naik
51 How to Visualize Multiple Linear Regression in python
How to Visualize Multiple Linear Regression in python
Krish Naik
52 K Nearest Neighbour Easily Explained with Implementation
K Nearest Neighbour Easily Explained with Implementation
Krish Naik
53 Predicting Heart Disease using Machine Learning
Predicting Heart Disease using Machine Learning
Krish Naik
54 Predicting Lungs Disease using Deep Learning
Predicting Lungs Disease using Deep Learning
Krish Naik
55 Stock Sentiment Analysis using News Headlines
Stock Sentiment Analysis using News Headlines
Krish Naik
56 Random Forest(Bootstrap Aggregation) Easily Explained
Random Forest(Bootstrap Aggregation) Easily Explained
Krish Naik
57 Voting Classifier(Hard Voting and Soft Voting Classifier)
Voting Classifier(Hard Voting and Soft Voting Classifier)
Krish Naik
58 Credit Card Fraud Detection using Machine Learning from Kaggle
Credit Card Fraud Detection using Machine Learning from Kaggle
Krish Naik
59 Hyperparameter Optimization for Xgboost
Hyperparameter Optimization for Xgboost
Krish Naik
60 Tutorial 45-Handling imbalanced Dataset  using python- Part 1
Tutorial 45-Handling imbalanced Dataset using python- Part 1
Krish Naik

Related Reads

📰
Stop Writing 40-Method Repositories: The Specification Pattern in Symfony
Learn to avoid fat repositories in Symfony by applying the Specification Pattern to improve code organization and maintainability
Medium · Programming
📰
You Don’t Have a Performance Problem — You Have a Design Problem
Most performance issues stem from design flaws, not coding errors, and can be solved by reevaluating system architecture
Medium · Programming
📰
Migrating to Astro, How I Built a Bilingual Static Blog
Learn how to migrate to Astro and build a bilingual static blog with features like content collections and zero-JS patterns
Dev.to · 灯里/iku
📰
Make an Outbox Relay Lease Expire Without Violating Delivery Invariants
Learn how to model duplicate delivery from an expired relay lease without violating delivery invariants
Dev.to · Robin
Up next
Gimbal Controlled Model Rocket Design Overview
Making Made Easy
Watch →