Python Sort the Elements of a Given List by Size
In Python, we can use the built-in sort() The method or the sorted() function sorts the elements in a list.sort() The method modifies the original list directly, while the sorted() function returns a new sorted list and leaves 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 a list (in-place sorting)
numbers.
sort
(
)
(
"List sorted with the sort() method:"
,
numbers
)
Use the sorted() function to sort a list (returns a new list)
sorted_numbers
=
sorted
(
numbers
)
(
"List sorted with the sorted() function:"
,
sorted_numbers
)
Code analysis:
numbers.sort():sort()The method sorts the listnumbersin place, that is, it modifies the original list directly.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]
Python3 Examples