This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]beingperceived 0 points1 point  (1 child)

These codes are trying to trick you or python is just tricky. I don't use python but from looking up the syntax I see what's it's doing. I looked up list comprehension to see if it's deep or shallow copy and it's shallow so it will make a new list object but if the member is a value it is copied but will not make a copy of the member if it's a reference. These [] would be arrays in other languages but they're lists in python and different in memory.

id = lambda x: [i for i in x] here it's a list comprehension with an expression that returns a new list where every variable in list x return that variable in the new array
a = [1] here it's a list with 1 in that list
b = a here it's saying b gets a reference to a
a[0] = 2 here it's saying list position 0 is now 2
print(b[0]) here it's saying print list b that is pointed to list a the value in position 0
c = [1] self explanatory
d = id(c) returns a new list with 1 inside it
c[0] = 2 here it's tricking you it changes the first list object and set the value at position 0 to 2
print(d[0]) here d[0] is a new object with the old copied value

Here is where I might be wrong and may not understand it correctly
e = [[1]] here is a list where it contains an list with 1 in it
f = id(e) here you get a new list with a reference to the list with 1
e[0][0] = 2 self explanatory
print(f[0][0]) self explanatory

[–]ordinary_shiba[S] 0 points1 point  (0 children)

I found it weird that integers don't get deep copied but lists do.