Shallow and Deep Copy Python Programming Tutorial

  Рет қаралды 95,143

Tejas Patel

Tejas Patel

Күн бұрын

In python you can't simply use the = to copy something from one variable/object to another variable/object. To truly copy something you need to make use of the shallow copy or deep copy, this python tutorial shows you why.

Пікірлер: 98
@alexchang435
@alexchang435 5 жыл бұрын
Very clear and concise. Just enough information and examples to get your point across, but not too much information can clutter and confuse understanding. Thank you.
@liamhan8145
@liamhan8145 3 жыл бұрын
Great video but there's one thing that wasn't clearly explained and reading through the comments, I think others were a little confused by this. TLDR When making modifications on the elements, you have to be check whether the child element (the element you want to modify) is mutable or immutable. Depending on this, the result you get back can be different. Example below ----------------------------------------------- When you shallow copy arr1 (as shown below), you get arr2. arr1 and arr2 have DIFFERENT id but referencing the same child elements. aka. each child have the same id arr1 = [1,2,[3,4],5] arr2 = copy.copy(arr1) id(arr1) == id(arr2) => FALSE arr1 == arr2 => TRUE id(arr1[0]) == id(arr2[0]) => TRUE id(arr1[1]) == id(arr2[1]) => TRUE id(arr1[2]) == id(arr2[2]) => TRUE id(arr1[3]) == id(arr2[3]) => TRUE ----------------------------------------------------- Let's modify one of the elements. arr1[0] = "a" when you now print arr1 and arr2 you'll get the result as shown below print(arr1[0]) => ['a', 2, [3, 4], 5] print(arr2[0]) => [1, 2, [3, 4], 5] The reason that the first element changed for arr1 but not for arr2 is because the first element `1` is an int which is immutable. Therefore, when you "modify" it from `1` to "a", you essentially create a new string object and now the first element of arr1 is pointing to that new object "a". But the first element of arr2 is still pointing at `1`. ----------------------------------------------------- Let's now modify an element in the list arr1[2][0] = "b" when you now print arr1 and arr2 you'll get the result as shown below print(arr1[0]) => ['a', 2, ['b', 4], 5] print(arr2[0]) => [1, 2, ['b', 4], 5] This is what really tripped me first! But this is also due to mutability/immutability. Now (looking at the arr1 before modifying), arr1[2] is [3,4] which is a list, hence mutable. So, modifying that list won't create a new object like above. Therefore, modifying any element inside the list is being shown on both arr1 and arr2. ----------------------------------------------------- Long story short, shallow copy does create a copy of a desired collection object. But it is populated with references to the child objects from the original. And depending on whether the element is mutable or not, it can have a very different result Please let me know if I've made any mistakes. Cheers
@yokeshchowdary1550
@yokeshchowdary1550 2 жыл бұрын
Clearly explained bro 🥳🥳🥳🥳🥳🥳🔥🔥🔥🔥🔥thanks
@naveennoel9496
@naveennoel9496 2 жыл бұрын
Thanks!
@bencipherx
@bencipherx 2 жыл бұрын
Perfectly explained
@saimakhalil5137
@saimakhalil5137 Жыл бұрын
jazaKALLAH
@loggitdot
@loggitdot 4 жыл бұрын
I've been stuck on this for the past day. Your video has cleared this up perfectly. 7/7 would watch again.
@jyotiprakashdas9882
@jyotiprakashdas9882 6 жыл бұрын
This is what I was searching for a long time. clear and on point explanation . Thanks and keep going.
@TejasPatelYT
@TejasPatelYT 6 жыл бұрын
Thank you, will be starting again soon hopefully (:
@adarshsasidharan254
@adarshsasidharan254 4 жыл бұрын
I wasted a lot of time understanding this, now I finally found this video. Thanks
@Alphredis
@Alphredis 3 жыл бұрын
Struggeling with Python for weeks. You just solved all my problems
@gauravnikalje802
@gauravnikalje802 3 жыл бұрын
Bro you explained so well in a very short time. Saved myself a lot of time. Thanks.
@moglimogify
@moglimogify 3 ай бұрын
Stole this explanation for tech interviews, thank you :)
@taiwoadebisi9315
@taiwoadebisi9315 2 жыл бұрын
Saw other videos on the same topic that went from 12 minutes to 15 minutes. Amazing how you summarize it in less than 4. Thank you.
@kiffbeatz
@kiffbeatz Жыл бұрын
Brilliant. Short and concise. Thank you.
@amadeujoaquim2543
@amadeujoaquim2543 Жыл бұрын
Thanks a lot. Theres no way to make things clear than this.
@abdullahassamialnoor2779
@abdullahassamialnoor2779 8 ай бұрын
Concise and helpful. Kudos!
@blaze9558
@blaze9558 Жыл бұрын
Oh god that was awesome.. You legit explained so much , so clearly in just few minutes.. Hats off man
@subinkv6849
@subinkv6849 8 ай бұрын
Good explanation..Thank you..
@cruepprich
@cruepprich 5 жыл бұрын
Short and sweet! Thanks!
@srenjensen2836
@srenjensen2836 Жыл бұрын
Clear and concise. Great video
@handokosupeno5425
@handokosupeno5425 Жыл бұрын
Very clear explanation. Thanks bro you are lifesaving
@mohsinalisep
@mohsinalisep 2 жыл бұрын
There's this one thing to consider. If the elements inside the list are of primitive datatype, their reference won't be copied cus primitive datatypes are copied by value. So, to see shallow copy in action you should use non-primitive datatypes that are list, tuples or dictionaries for the elements of the list.
@arneishprateek6444
@arneishprateek6444 Жыл бұрын
More precisely, the elements of the list must be "mutable" objects to see shallow copy in action (see Liam Han's comment below)
@deeek92
@deeek92 Жыл бұрын
Clear and concise explanation!
@baoyandong2848
@baoyandong2848 4 жыл бұрын
the voice is really clean haha so I liked the video 3 s into it. The content is concise.
@doughntworry
@doughntworry 5 жыл бұрын
clear and concise. thanks a lot
@ngzushen4833
@ngzushen4833 3 жыл бұрын
short and informative. give good examples, easy to understand.
@shashishekhar----
@shashishekhar---- 2 жыл бұрын
Very good and helpful explaination and demonstration my brother 🙏👍.
@EW-mb1ih
@EW-mb1ih 2 жыл бұрын
Straight to the point, thank you sir
@venkatdevireddy650
@venkatdevireddy650 6 жыл бұрын
very good explanation in just 3 minutes
@kbprojekty
@kbprojekty 5 жыл бұрын
Thanks for the explanation!
@romankalenov9007
@romankalenov9007 4 жыл бұрын
Brilliantly clear, thanks
@keinermendoza4631
@keinermendoza4631 Жыл бұрын
Thanks for the explanation, quite enlightening. 👍
@saurabhchaturvediscientist
@saurabhchaturvediscientist 5 жыл бұрын
Thank you so much! The explanation was clear and concise!
@Ben-ZionMegido
@Ben-ZionMegido Жыл бұрын
Great explanation, thanks
@Vishnuraghutkm
@Vishnuraghutkm 4 жыл бұрын
simple good explanation
@nischaysingh
@nischaysingh 2 жыл бұрын
To the point video. Now a days, even for a 2 min video creators consume one minute saying subscribe to my youtube channel 🤣
@sandyhan4829
@sandyhan4829 4 жыл бұрын
very clear! thank you
@Ali-hr8qu
@Ali-hr8qu 2 жыл бұрын
just wowly explained
@userozancinci
@userozancinci 4 жыл бұрын
this is so clear thanks!
@as00060
@as00060 6 жыл бұрын
I did some testing with the module, and I found that after copy.copy if I am making changes in the original list, the changes happen only in that list. The new list has no effect, and vise a versa. However, as shown by you. When we replaced the 2nd element of the first sublist, the changes are happening in both original and new list. Isn't that contradicting?
@TejasPatelYT
@TejasPatelYT 6 жыл бұрын
Hi thanks for the comment :) When you say you made changes to that list you must have only changed the 1st dimension elements ie some_list[3] = 'xyz'. So you changed the reference of the 4th element to something else which is why the other list remains the same. There is no contradiction here. The copy.copy only creates a new object but the elements of that object are references to the original elements. So both lists change if you make a change to the element that is being referenced, so making a change to the sublist ie some_list[3][2] = 'xyz' would result in the referenced element to change. Since both new and old list reference the same element you will see the change in both. Hope that clears up your doubts
@sasidharnaidu4507
@sasidharnaidu4507 Жыл бұрын
Copy.copy gives a shallow copy, one level deep. If you want to have a strict new copy, even for the constituent elements of the list, you can go for deep copy.
@polusanisriman8424
@polusanisriman8424 Жыл бұрын
Wow.. It's a good video!
@JasonRobards2
@JasonRobards2 2 жыл бұрын
When would you use a shallow copy over a deep copy? In other words, what is the use of this whole distinction?
@Andres-Estrella
@Andres-Estrella Жыл бұрын
so if there are no nested lists a shallow and a deep copy accomplish the same result?
@VascoCC95
@VascoCC95 4 жыл бұрын
Very good! Thanks a lot!
@keshavdk3080
@keshavdk3080 3 жыл бұрын
This video gave the clear understanding of Shallow copy and Deep copy. Thank you for the video. Can i know the real time use cases of these functions ?
@cy9987
@cy9987 2 жыл бұрын
Right on point, thank you!
@Enthsz
@Enthsz 8 ай бұрын
Thanks help a lot
@pranayyanarp4118
@pranayyanarp4118 5 жыл бұрын
helped a lot. thanks man.
@TejasPatelYT
@TejasPatelYT 5 жыл бұрын
Thanks for watching (:
@indiannewyorkbabies6872
@indiannewyorkbabies6872 4 жыл бұрын
So in case of Non-compound objects, both shallow and deepcopy does the same job??? And they are different in case of compound objects child object(element change). Is this right ??
@no_life_wth_leafras949
@no_life_wth_leafras949 2 жыл бұрын
finaly, what's the differencec between x = x and x = copy.copy(x) ?
@SahilThakur26
@SahilThakur26 5 жыл бұрын
thanks for explaining. i get that its relevant for compound objects(objects containing objects) but interger is also an object in python, so why doesn't it work on them? like if you try this on list of numbers than just nested list, it doesn't work. Could you please comment on this to clear my doubt
@TejasPatelYT
@TejasPatelYT 5 жыл бұрын
What doesn't work exactly? A shallow copy on a list of number references? ie x = 3 y = 6 nums = [x, y] ?
@satellitesage2487
@satellitesage2487 5 жыл бұрын
Tejas Patel import copy spam = [1, 2, 3] cheese = copy.copy(spam) cheese[0] = 77 print(spam) print(cheese) ----OUPUT--- [1, 2, 3] [77, 2, 3] We have the same question. If shallow copy means just references to each object, how come this does not apply to noncompund objects, i.e, say just a list of integers? (Demonstrated by the code above).
@TejasPatelYT
@TejasPatelYT 5 жыл бұрын
Ah yes I probably should of been more clear. Shallow copy would copy over the references of CHILD OBJECTS of a compound object but populate them in a new compound object, non compound object would not have this as there are no child objects so it would just construct a new object for it.
@satellitesage2487
@satellitesage2487 5 жыл бұрын
Tejas Patel Thank you so much for clearing my confusion!
@ViratHarish
@ViratHarish 5 жыл бұрын
Awesome sir
@pavittarkumarazad3259
@pavittarkumarazad3259 4 жыл бұрын
WOW! Just what I wanted :)
@greyhnd001
@greyhnd001 4 жыл бұрын
I am having trouble using datetime to print to a notepad after running my os telnet python script I want it to append the date and time at the end of the notepad. We have had some instances of people copying our work so the datetime will help stop that.
@ianlawson94
@ianlawson94 3 жыл бұрын
Thank you
@janmichaelbesinga3867
@janmichaelbesinga3867 4 жыл бұрын
thanks!
@shirleymoon9934
@shirleymoon9934 2 жыл бұрын
very clear!
@mihaistoian_
@mihaistoian_ 3 жыл бұрын
Thank you!
@Fine_Mouche
@Fine_Mouche 3 жыл бұрын
i ended the video, why `new_list = [a,b,c]` work with `copy.copy()` if the reference stay the same ?
@Fine_Mouche
@Fine_Mouche 3 жыл бұрын
this video answered me : kzbin.info/www/bejne/iIKZhqWViZV6abs
@mikijasar2594
@mikijasar2594 4 жыл бұрын
Dear Petel, please can you explain to me in the example below why the id of the elements inside the list with shallow copy and deep copy is the same ?? import copy a = [[1,2],[3,4]] z = copy.copy(a) print(a) print(id(a[1][0]),'a 1-0') print(id(z[1][0]),'z 1-0') y = copy.deepcopy(a) print(id(a[1][0]),'a 1-0') print(id(y[1][0]),'y 1-0') Output: [[1, 2], [3, 4]] 267638992 a 1-0 267638992 z 1-0 267638992 a 1-0 267638992 y 1-0 Thanks in advance
@viddeshk8020
@viddeshk8020 9 ай бұрын
Why a b c is not changed in original list?
@vn7512
@vn7512 4 жыл бұрын
I'm confused couldn't you just use an already build-in function copy? new_list = old_list.copy() ?
@sonnyhull1213
@sonnyhull1213 2 жыл бұрын
Thanks alot!
@srik86
@srik86 3 жыл бұрын
I don’t understand reason behind having shallow copy as a function. It’s neither completely a copy nor completely a reference. Is it there just to confuse people? Why only child objects of a nested list are referenced ? What’s the idea behind this
@priyamvashi2187
@priyamvashi2187 2 ай бұрын
Thank you bhai
@tarams7775
@tarams7775 5 жыл бұрын
Could you please share an example for 1D list?
@sethatkins3731
@sethatkins3731 5 жыл бұрын
y tho?
@ethanlimrx
@ethanlimrx 4 жыл бұрын
Are there any benefits to using a shallow copy? Why not just have deepcopy as standard?
@vn7512
@vn7512 4 жыл бұрын
my exact thought
@thirumala_reddy
@thirumala_reddy 5 жыл бұрын
nice explanation thank u
@43SunSon
@43SunSon 2 жыл бұрын
good video, pika pika
@briansteven6318
@briansteven6318 2 жыл бұрын
thank you bruh
@shahzebahmad7866
@shahzebahmad7866 4 жыл бұрын
Tq
@acfry
@acfry 10 ай бұрын
thank
@dalinefissi9377
@dalinefissi9377 4 жыл бұрын
very clear gg
@gauravpratapsingh1575
@gauravpratapsingh1575 4 жыл бұрын
I tried this with only one value like: X=5 Y=X Now Y=6 But in the output X remains same it doesn't changes to 6 why?
@shyamgj0091
@shyamgj0091 4 жыл бұрын
It doesnt work bcos u are initialising Y to X so Y stores the value of X which is 5. Now when u tell Y = 6, Y simply gets updated to 6 and X doesnt change
@ajinzrathod
@ajinzrathod 4 жыл бұрын
Instead just use *new_list = old_list[:]* This is slicing Slicing lists does not generate copies of the objects in the list; it just copies the references to them.
@Avinash-st8hd
@Avinash-st8hd 3 жыл бұрын
Wow
@shinkansen1907
@shinkansen1907 4 жыл бұрын
Dude you talk like a comic book villain, nice video tho thx.
@taihatranduc8613
@taihatranduc8613 2 жыл бұрын
found the bug after hours
@akhilnadhpc
@akhilnadhpc 6 жыл бұрын
Downvote for not explaining why shallow copy works only in nested list not in single 1D list
@TejasPatelYT
@TejasPatelYT 6 жыл бұрын
Thanks for your feedback :) I was hoping the shallow copy of the nested list example, showing the whole first element of the list being replaced, would also resemble the same as replacing the first element of a 1D list. So a shallow copy would work with a 1D list, it's when you have multiple nested objects is when a shallow copy does not create a copy of everything.
@4eversuju
@4eversuju 4 жыл бұрын
@@TejasPatelYT Thank you so much! it really helped me after your explaination here!
@hardline_fc
@hardline_fc 8 ай бұрын
Thank you
Shallow Copy Vs Deep Copy in Python
12:49
Krish Naik
Рет қаралды 80 М.
Python: Deep Copy vs Shallow Copy
7:59
Programming and Math Tutorials
Рет қаралды 3 М.
Don’t Choose The Wrong Box 😱
00:41
Topper Guild
Рет қаралды 55 МЛН
She made herself an ear of corn from his marmalade candies🌽🌽🌽
00:38
Valja & Maxim Family
Рет қаралды 16 МЛН
Python Tutorial: if __name__ == '__main__'
8:43
Corey Schafer
Рет қаралды 2 МЛН
Mutable vs Immutable - Python
21:21
Tech With Tim
Рет қаралды 22 М.
Learn Python OOP in under 20 Minutes
18:32
Indently
Рет қаралды 139 М.
“typing” is getting deprecated in Python
7:20
Indently
Рет қаралды 78 М.
25 nooby Python habits you need to ditch
9:12
mCoding
Рет қаралды 1,8 МЛН
Python Decorators in 15 Minutes
15:14
Kite
Рет қаралды 454 М.
Javascript Array and Object Cloning: Shallow or Deep?
8:39
Jack Herrington
Рет қаралды 12 М.
PLEASE Use These 5 Python Decorators
20:12
Tech With Tim
Рет қаралды 124 М.
you need to learn Python RIGHT NOW!! // EP 1
17:42
NetworkChuck
Рет қаралды 2,5 МЛН