Python List Sorting: sort() vs sorted() Methods

In Python, you can use the sort() method of a list to sort it. This method can sort the list in ascending order by default, or you can specify the reverse parameter as True to sort it in descending order.

For example:

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
my_list.sort()  # 默认升序排序
print(my_list)

my_list.sort(reverse=True)  # 降序排序
print(my_list)

In addition to the sort() method, Python also offers the built-in sorted() function to sort lists, which returns a new sorted list without altering the original list’s order.

For example,

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_list = sorted(my_list)  # 默认升序排序
print(sorted_list)

sorted_list = sorted(my_list, reverse=True)  # 降序排序
print(sorted_list)
bannerAds