Ordenar listas
Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.
Suppose we have an unordered list
list = [1, 4, 7, 2, 5, 8, 3, 6, 9]print(list)
[1, 4, 7, 2, 5, 8, 3, 6, 9]
And we want to sort it, so we use the sort()
method
list.sort()print(list)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
The problem with the sort()
method is that it modifies the original list. If we print the list again, we see that it is sorted, and we no longer have the original list.
print(list)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
We recreate the original list
list = [1, 4, 7, 2, 5, 8, 3, 6, 9]print(list)
[1, 4, 7, 2, 5, 8, 3, 6, 9]
To sort a list without modifying it, we can use the sorted()
function
print(sorted(list))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
If we now print the original list again, we see that it has not changed.
print(list)
[1, 4, 7, 2, 5, 8, 3, 6, 9]
The same happens if we want to sort it in reverse order, we can use the .reverse()
method.
list.reverse()print(list)
[9, 6, 3, 8, 5, 2, 7, 4, 1]
If we print the list we see that it is ordered in reverse order and not as we had it at the beginning.
print(list)
[9, 6, 3, 8, 5, 2, 7, 4, 1]
We create the original list again
list = [1, 4, 7, 2, 5, 8, 3, 6, 9]print(list)
[1, 4, 7, 2, 5, 8, 3, 6, 9]
If we want to sort a list without modifying it, we use the sorted()
function again, but with the argument reverse=True
.
print(sorted(list, reverse=True))
[9, 8, 7, 6, 5, 4, 3, 2, 1]
If we now print the original list, we see that it has not changed.
print(list)
[1, 4, 7, 2, 5, 8, 3, 6, 9]