THIS Feature Made Me Cry In Python #code #python #programming
47,425
Published 2024-05-18
All Comments (21)
-
It's not only Python, all languages have this distinction between a shallow copy and a deep copy
-
At my last job, we had a huge data model represented as a tree where most of the nodes were immutable but some were mutable and we wanted the immutable ones to be not copied at all (just return the reference) and the others to be recursively copied, so I made an @immutable decorator that could be used to abort copying / deep copying, and it worked very well and drastically reduced memory use and increased performance.
-
Great explanation, thanks
-
I just tested it. [:] creates a shallow copy. >>> a = [0,['a', 'b'], 2] >>> b = a[:] >>> b[1][0] = 'Bob' >>> print(a) [0, ['Bob', 'b'], 2] >>> print(b) [0, ['Bob', 'b'], 2]
-
What does the = do in the bracket?
-
Given Python's behavior shown in the video, I thought "b=a.copy()" would just make b a pointer to the "a" memory chunk, but the behavior shown in the video refers to a nested list. If a=[1,2,3] and b=a.copy(), then b[1]=5, say, makes b=[1,5,3], but still a=[1,2,3] (use appropriate "print" statements), so "b" is not just a pointer to variable "a" under b=a.copy(). I honestly don't know what's going on.
-
I had this exact problem with a game that I made and it took me forever to figure out why it was doing this
-
I use both C++ and python, and if you do a vector of variant in C++, copy works. Copy in C++ is deep copy else we talk of reference.
-
when i first started coding i used to just use a for loop to copy them so this wouldnt happen
-
This happens for lists inside dictionaries too!!!, how am I just learning this 0-0
-
down side of not being able to use pointers
-
Array names are essentially pointers! It's an interesting (often annoying) feature, but I can see why one would use it.
-
Did you cry because Python made it so easy for you to do a deep copy? I don't get it.
-
you would think that copy should be making a deepcopy and shallowcopy be a separate function , not the other way around
-
Wait....that's a Python built-in?! π€―π€―π€―π€―
-
yuss, i used this method to create child nodes for my minimax algorithm
-
b = a[:] may also work
-
You can design your own recursive deepcopy function.
-
i feel like doing b = a[:] could work too, but maybe i'm wrong i didn't test it with a nested container
-
how about b = a?