Python Sort Elements of a Given List by Size

Document 对象参考手册Python3 Examples

In Python, we can use the built-insort()method orsorted()function to sort the elements in the list.sort()The method modifies the original list directly, while thesorted()function returns a new sorted list, leaving the original list unchanged.

Example

# Define a list
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# Use the sort() method to sort the list (in-place sort)
numbers.sort()
print("List sorted using the sort() method:", numbers)

# Use the sorted() function to sort the list (returns a new list)
sorted_numbers = sorted(numbers)
print("List sorted using the sorted() function:", sorted_numbers)

Code analysis:

  1. numbers.sort():sort()The method sorts the listnumbersin place, i.e., it directly modifies the original list.
  2. sorted(numbers):sorted()The function returns a new sorted list, and the original listnumbersremains unchanged.

Output result:

使用 sort() 方法排序后的列表: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
使用 sorted() 函数排序后的列表: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

Document 对象参考手册Python3 Examples

Other Extensions