Home >Backend Development >Python Tutorial >How to sort a list in Python

How to sort a list in Python

coldplay.xixi
coldplay.xixiOriginal
2021-03-05 11:44:3144734browse

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.

How to sort a list in Python

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

How to sort a list in Python

2. First, we call the sort method of the list, but this method has no return value, so the output is None

How to sort a list in Python

3. Then we output the original list , found that the original list has changed

How to sort a list in Python

4. Then we use the sorted method to sort the list, and find that when outputting directly, the output list is a sorted list

How to sort a list in Python

5. Then output the original list and find that the original list is not sorted

How to sort a list in Python

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn