Home  >  Article  >  Backend Development  >  How to sort a list in python

How to sort a list in python

(*-*)浩
(*-*)浩Original
2019-06-28 09:49:4017283browse

Python lists have a built-in list.sort() method that can directly modify the list and sort it. There is also a sorted() built-in function, which constructs a new sorted list from an iterable object.

How to sort a list in python

list.sort() function is used to sort the original list. If parameters are specified, the comparison function specified by the comparison function is used.

Grammar: (Recommended learning: Python video tutorial)

list.sort( key=None, reverse=False)

Parameters

key - - Mainly used for comparison of elements, with only one parameter. The parameters of the specific function are taken from the iterable object, and an element in the iterable object is specified for sorting. reverse -- sorting rule, reverse = True for descending order, reverse = False for ascending order (default).

Return value

This method has no return value, but it will sort the objects in the list.

Example

#!/usr/bin/python
aList = ['Google', 'Runoob', 'Taobao', 'Facebook']
sorted(aList)
aList.sort()
print ( "List : ", aList)

For the Python built-in function sorted(), first compare it with the member function list.sort() in list (list). In essence, the sorting of lists is similar to the sorting of the built-in function sorted, but the list.sort() method is only defined for lists, while the sorted() function can accept any iterable object.

The main difference is that list.sort() operates on an existing list, and can then change the list being operated on. The built-in function sorted returns a new list instead of an operation based on the original one.

For more Python-related technical articles, please visit the Python Tutorial column to learn !

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