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

Python sorted() Function

Python sorted() Function

Python built-in function Python built-in function


Description

sorted() The function sorts all iterable objects.

Difference between sort and sorted:

sort is a method applied to list, while sorted can sort any iterable object.

The sort method of list operates on the existing list and returns no value, whereas the built-in sorted function returns a new list rather than operating on the original.

Syntax

sorted syntax:


sorted(iterable, cmp=None, key=None, reverse=False)

Parameter Description:

Return Value

Returns the reordered list.

Example

The following examples demonstrate how to use sorted:

a

=

[

5

,

7

,

6

,

3

,

4

,

1

,

2

]

b

=

sorted

(

a

)

Keep the original list

a

[

5

,

7

,

6

,

3

,

4

,

1

,

2

]

b

[

1

,

2

,

3

,

4

,

5

,

6

,

7

]

L

=

[

(

'

b

'

,

2

)

,

(

'

a

'

,

1

)

,

(

'

c

'

,

3

)

,

(

'

d

'

,

4

)

]

sorted

(

L

,

cmp

=

lambda

x

,

y

:

cmp

(

x

[

1

]

,

y

[

1

]

)

)

Using the cmp function

[

(

'

a

'

,

1

)

,

(

'

b

'

,

2

)

,

(

'

c

'

,

3

)

,

(

'

d

'

,

4

)

]

sorted

(

L

,

key

=

lambda

x

:

x

[

1

]

)

Using key

[

(

'

a

'

,

1

)

,

(

'

b

'

,

2

)

,

(

'

c

'

,

3

)

,

(

'

d

'

,

4

)

]

students

=

[

(

'

john

'

,

'

A

'

,

15

)

,

(

'

jane

'

,

'

B

'

,

12

)

,

(

'

dave

'

,

'

B

'

,

10

)

]

sorted

(

students

,

key

=

lambda

s

:

s

[

2

]

)

Sort by age

[

(

'

dave

'

,

'

B

'

,

10

)

,

(

'

jane

'

,

'

B

'

,

12

)

,

(

'

john

'

,

'

A

'

,

15

)

]

sorted

(

students

,

key

=

lambda

s

:

s

[

2

]

,

reverse

=

True

)

In descending order

[

(

'

john

'

,

'

A

'

,

15

)

,

(

'

jane

'

,

'

B

'

,

12

)

,

(

'

dave

'

,

'

B

'

,

10

)

]

Python built-in function Python built-in function