sort
and sorted
Sort
and sorted
are mainly used when sorting list data. If you want to get only the sorted result without changing the original contents, you can use sorted
. Also, sorted
can be used for tuples and iterators. The difference in behavior is as follows.
a = [4, 6, 2, 8]
b = [5, 3, 9, 7, 1]
a.sort()
print(a)
print(sorted(b))
print(b)
Execution result
[2, 4, 6, 8] [1, 3, 5, 7, 9] [5, 3, 9, 7, 1]
reserved
reserved
is a function used when sorting in reverse order. Like the sorted
method, it is a function that returns only the sorted result without changing the content itself.
a = [4, 6, 2, 8]
print(reserved(a))
Execution result
[8, 6, 4, 2]
a = [4, 6, 2, 8]
print(sorted(a)[::-1])
Execution result
[8, 6, 4, 2]
Recommended Posts