One of the common things that you can notice in many tasks is the fact that you need to sort elements in a list. In fact, this can also be part of an interview that you may go through while applying for a job. Maybe not only sorting elements, but sorting elements fulfilling certain conditions.
There are in fact two built-in methods that you can use to sort elements in Python which are also quite popular and do not have to reinvent the wheel.
The first one is
sort() which can be used to
sort the original list, meaning that when you use it, you are
going to modify the list in which you are calling this method
on.
Let us see this with an example:
numbers = [1456, 12, 431, 831, 2]
numbers.sort()
print(numbers) # [2, 12, 431, 831, 1456]
There is another one called
sorted() that can be used
to sort elements of a list and returns a new list with the
sorted elements in it. The original list is going go remain
unchanged.
Here is an example of the previous list is sorted using
sorted():
numbers = [1456, 12, 431, 831, 2]
new_numbers = sorted(numbers)
print(new_numbers) # [2, 12, 431, 831, 1456]
As a recap, the difference between
sort() and
sorted() is that
sort() modifies the
existing list, whereas
sorted() returns a new
sorted list.