How to order elements in a list using Python?

In Python, you can use the built-in function sorted() to sort elements in a list.

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]

# 使用sorted()函数对列表进行排序
sorted_list = sorted(my_list)

print(sorted_list)

The output result is: [1, 1, 2, 3, 4, 5, 5, 6, 9]

You can see that the sorted() function will return a new sorted list, and the original list will not be modified. If you want to sort the original list, you can use the sort() method.

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]

# 使用sort()方法对列表进行排序
my_list.sort()

print(my_list)

The output result is: [1, 1, 2, 3, 4, 5, 5, 6, 9]

Using the sort() method will directly modify the original list and not return a new sorted list.

bannerAds