Create a Shallow Copy of a List
and then I’ll show you how you can create a shallow copy in Python. You can use a similar syntax to the one that didn’t work for what we’re intending to do, but instead of saying just
the_matrix = matrix, at the end of the original list, you’re going to use slice notation.
00:25 So open square brackets, close them and put a colon in between. Now, if you remember how slicing works, this shortcut says take everything that’s inside of the list, like from the beginning to the end.
So now you can do what you tried to do before, and it’ll work out. So if I now go ahead and say
the_matrix and change the element on index one to the names of the two movie characters, and then I can look at
the_matrix, and it does what you expect it to do.
Let’s try that out. I’ll start again with resetting. No, I don’t need to reset anything because
matrix still looks the same. Okay, if you now went ahead and you wanted to change inside of
the_matrix, you want to change also something in the first list that’s contained by
However, if you now look at
matrix, then you’ll see that
"Morpheus" also appears in here. And why is that? Because like I said before, the two separate list objects,
matrix only contain references to the other list objects in there.
And if you create a shallow copy like you did before using the slice notation, you don’t create separate objects from the containing lists. So if you look at
id(the_matrix), so the first element in
the_matrix, which is this list, or well now it looks like that it contains now
04:23 So the takeaway here is that shallow copies contain copied references. They don’t copy the objects inside of it, but they just contain a copied reference, which means that if you do a change to a mutable object in there, again, you’ll have the same issue that you’re changing the object.
Become a Member to join the conversation.