Home >Backend Development >Python Tutorial >How to sort a list in Python
How to sort the list in Python: 1. Call the sort method of the list, output the original list, and find that the original list has changed; 2. Use the sorted method to sort the list, and find that when outputting directly, the output list is sorted Good list.
The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.
How to sort a list in Python:
1. First, we need to know the two sorting methods in python, one is sorted and the other is sort
sort()
is a built-in method of the list. It has no return value. It is used to sort the list. The list changes
sorted
is a global built-in method with a return value. It returns a new object after sorting the iterable sequence, but the original sequence remains unchanged
2. First, we call the sort method of the list, but this method has no return value, so the output is None
3. Then we output the original list , found that the original list has changed
4. Then we use the sorted method to sort the list, and find that when outputting directly, the output list is a sorted list
5. Then output the original list and find that the original list is not sorted
6. Attached here is the code:
entry=[1,3,2,5,4,6,7] print(entry.sort()) #None print(entry) #[1, 2, 3, 4, 5, 6, 7] entry1=[1,3,2,4,5,6] print(sorted(entry1)) #[1, 2, 3, 4, 5, 6] print(entry1) #[1, 3, 2, 4, 5, 6] # sort()是列表内置的方法,没有返回值,是将列表排序 # sorted是全局内置的方法,有返回值,返回对可迭代序列排序后的新对象,但是原来的序列不变
Related free learning recommendations: python video tutorial
The above is the detailed content of How to sort a list in Python. For more information, please follow other related articles on the PHP Chinese website!