Here are a few simple examples to see the difference in action:
See the list of numbers here:
nums = [1, 9, -3, 4, 8, 5, 7, 14]
When calling sorted
on this list, sorted
will make a copy of the list. (Meaning your original list will remain unchanged.)
Let's see.
sorted(nums)
returns
[-3, 1, 4, 5, 7, 8, 9, 14]
Looking at the nums
again
nums
We see the original list (unaltered and NOT sorted.). sorted
did not change the original list
[1, 2, -3, 4, 8, 5, 7, 14]
Taking the same nums
list and applying the sort
function on it, will change the actual list.
Let's see.
Starting with our nums
list to make sure, the content is still the same.
nums
[-3, 1, 4, 5, 7, 8, 9, 14]
nums.sort()
Now the original nums list is changed and looking at nums we see our original list has changed and is now sorted.
nums
[-3, 1, 2, 4, 5, 7, 8, 14]