Sorted Numbers Copy (Solution)
00:00 I’ll start by creating this numbers list. Open, close, square bracket, and then count backwards from 4, 3, 2, 1.
00:10
And here’s the list. Now I want to create a copy of this numbers list using slice notation. So I’ll call the copy numbers_copy
and then assign it to numbers
.
00:24
Keep in mind that you want to use slice notation here to create a shallow copy. Otherwise, if you omit this [:]
and you just say numbers_copy = numbers
, then you’ll just create another reference to the same numbers
object.
00:40
So then sorting numbers_copy
like we’re going to do in a second, would also sort the object that numbers
points to because it would be the same object.
00:49
But in this case, we created a shallow copy and now I can go ahead and sort numbers_copy
. numbers_copy.sort()
.
01:00
Let’s look at numbers_copy
. And now this counts from one up to four. So it’s sorted by lowest integer first up to the highest one, and numbers
still goes the other way round.
01:12 So it starts with the highest integer and then goes down.
01:17 The one gotcha here is that you need to actually create a copy of the list. Otherwise, if you wouldn’t do that, then sorting one of the references would sort the object and then you would see the same effect when accessing it through the other reference.
Become a Member to join the conversation.