Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Sort the Elements of a Given List by Size

Python Sort the Elements of a Given List by Size

Document Object Reference Manual Python3 Examples

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

(

)

print

(

"List sorted with the sort() method:"

,

numbers

)

Use the sorted() function to sort a list (returns a new list)

sorted_numbers

=

sorted

(

numbers

)

print

(

"List sorted with the sorted() function:"

,

sorted_numbers

)

Code analysis:

  1. numbers.sort():sort() The method sorts the list numbers in place, that is, it modifies the original list directly.
  2. sorted(numbers):sorted() The function returns a new sorted list, and the original list numbers remains 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 Object Reference Manual Python3 Examples