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

Python3 List sort() Method

Python3 List sort() Method

Python3 Lists The Python3 list


Description

The sort() function sorts the original list; if a parameter is given, it uses the comparison function specified.

Syntax

sort() method syntax:


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

Parameters

Parameters

Return Value

This method has no return value, but sorts the objects in the list.

Example

The following example shows how to use the sort() function:

Example

#!/usr/bin/python

aList

=

[

'

Google

'

,

'

Runoob

'

,

'

Taobao

'

,

'

Facebook

'

]

aList

.

sort

(

)

print

(

"

List :

"

,

aList

)

The output of the above example is:


List :  ['Facebook', 'Google', 'Runoob', 'Taobao']

The following example outputs the list in descending order:

Example

#!/usr/bin/python

-- coding: UTF-8 --

List

vowels

=

[

'

e

'

,

'

a

'

,

'

u

'

,

'

o

'

,

'

i

'

]

Descending

vowels

.

sort

(

reverse

=

True

)

Output result

print

(

'

Descending output:

'

,

vowels

)

The output of the above example is:


降序输出: ['u', 'o', 'i', 'e', 'a']

The following example shows how to output a list sorted by a specified element of its items:

Example

#!/usr/bin/python

Get the second element of the list

def

takeSecond

(

elem

)

:

return

elem

[

1

]

List

random

=

[

(

2

,

2

)

,

(

3

,

4

)

,

(

4

,

1

)

,

(

1

,

3

)

]

Sort by the second element

random

.

sort

(

key

=

takeSecond

)

Output category

print

(

'

Sorted list:

'

,

random

)

The output of the above example is:


排序列表:[(4, 1), (2, 2), (1, 3), (3, 4)]

Python3 Lists The Python3 list