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

Python List sort() method

Python List sort() method

Python Lists Python Lists


Description

sort() The function sorts the original list. If a parameter is specified, it is sorted using the comparison function specified by that parameter.

Syntax

sort() method syntax:



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

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

-- coding: UTF-8 --

aList

=

[

'

123

'

,

'

Google

'

,

'

Runoob

'

,

'

Taobao

'

,

'

Facebook

'

]

;

aList

.

sort

(

)

;

print

(

"

List :

"

)

print

(

aList

)

The output of the above example is:



List : 

['123', '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:

'

)

print

(

vowels

)

The output of the above example is:



# Descending order output:

['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

-- coding: UTF-8 --

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:

'

)

print

(

random

)

The output of the above example is:



Sort list:

[(4, 1), (2, 2), (1, 3), (3, 4)]

Python Lists Python Lists