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

Python Sort a List Using a lambda Expression

Python Sort a List Using a lambda Expression

Document Object Reference Manual Python3 Examples

In Python, a lambda expression is a way to create anonymous functions, typically used when a simple function is needed but you do not want to formally define one. Using lambda expressions makes it convenient to sort lists, especially when sorting based on a specific condition or attribute.

The following is an example of sorting a list using a lambda expression:

Example

Define a list containing tuples, each tuple containing a name and an age

people

=

[

(

'Alice'

,

25

)

,

(

'Bob'

,

20

)

,

(

'Charlie'

,

30

)

,

(

'David'

,

22

)

]

Use a lambda expression to sort by age

sorted_people

=

sorted

(

people

,

key

=

lambda

x: x

[

1

]

)

print

(

sorted_people

)

Code analysis:

Output result:


[('Bob', 20), ('David', 22), ('Alice', 25), ('Charlie', 30)]

As you can see, the list is sorted by age from smallest to largest.

Document Object Reference Manual Python3 Examples