THIS Feature Made Me Cry In Python #code #python #programming

preview_player
Показать описание
This feature made me cry in Python #code #python #programming
Рекомендации по теме
Комментарии
Автор

It's not only Python, all languages have this distinction between a shallow copy and a deep copy

BenoitCOMPERE
Автор

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.

vorpal
Автор

you would think that copy should be making a deepcopy and shallowcopy be a separate function, not the other way around

danutmh
Автор

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]

ElementEvilTeam
Автор

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.

olivierDurand-zhvu
Автор

I had this exact problem with a game that I made and it took me forever to figure out why it was doing this

fredtrunce
Автор

down side of not being able to use pointers

rawesomeness_
Автор

yuss, i used this method to create child nodes for my minimax algorithm

firebolt
Автор

This happens for lists inside dictionaries too!!!, how am I just learning this 0-0

classmanOfficial
Автор

when i first started coding i used to just use a for loop to copy them so this wouldnt happen

emre_ez
Автор

So then what is the point of having a copy method on list if b = a.copy() is equivalent to just b = a ?

leokillerable
Автор

Array names are essentially pointers! It's an interesting (often annoying) feature, but I can see why one would use it.

raiyaanshaikh
Автор

Would `list.copy()` be enough if there are no nested lists inside?

xsamueljr
Автор

Its because .copy() points to memory location.

luluw
Автор

i feel like doing b = a[:] could work too, but maybe i'm wrong i didn't test it with a nested container

dragweb
Автор

Wait....that's a Python built-in?! 🤯🤯🤯🤯

robinpipslayertekprofitsfa
Автор

I think you'll need recursive copy

javiarfasyah
Автор

You can design your own recursive deepcopy function.

tomasslavik
Автор

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.

midlander
Автор

I don't even use copy or deep copy
B=list(a)

staywithmeforever
visit shbcf.ru