0
Can somebody explain the output of this list operation?
I got this in the Challanges: a=[1,[2,3]] b=a[:] print(b) a[0]=3 a[1][1]=5 print(b) #Output is [1,[2,5]] Why isn't the output [3, [2,5]]? I understand th reason is in the semicolon, so that it's not the same to write b=a and b=a[:]. But this is what I don't understand :-)
4 Réponses
+ 2
a[:] makes a shallow copy. It takes all the references in a and puts them into a new list b.
So when you change an element of a, like in line 4, b will not know that, and not change.
In line 5, you change an element of the *inner* list - and this is just another reference to the same inner list in a.
I have recently written about the topic. I'd be happy if you take a look:
https://code.sololearn.com/c89ejW97QsTN/?ref=app
+ 3
Thank you! 🙂
I think you got how it works, but only once again about the term 'shallow copy':
The opposite is 'deep copy'. This means, that however deep (multidimensional) an object might be, it gets actually copied down to the innermost item.
a = [[], []]
b = a[:]
This is a shallow copy because only the outermost object is copied, the outer list.
So although b is a separate list, both the inner lists are not copied, but are only other references to the very same inner lists as in a.
Now if instead I had written:
b = []
for list_ in a:
b.append(list_[:])
Now I have copied the outer list AND made copies from the inner lists and put them in there.
So here everything to the bottom of it is copied, making it a deep copy.
+ 2
Thank you very much, HonFu!
So, if I understood correctly (and using your examples), the list a in the case above is something similar to this:
twins=["lucy","betty"]
a=["john",twins]
So, by doing b=a[:]
I create another list (b) which copies not the elements, but the references to the elements of (a): a string (shallow copy) and a list (not shallow copy).
Very clear article!
+ 1
Great!
Thank you again, so much.