Python Sort a List Using a lambda Expression
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
]
)
(
sorted_people
)
Code analysis:
peopleis a list containing tuples, each tuple containing two elements: a name and an age.sorted()function is used to sort the list.keyparameter specifies the basis for sorting; here we uselambda x: x[1]to specify sorting by the second element of the tuple (i.e., the age).lambda x: x[1]is an anonymous function that accepts a parameterx(each tuple in the list) and returnsx[1](i.e., the second element of the tuple, the age).sorted_peopleis the sorted list.
Output result:
[('Bob', 20), ('David', 22), ('Alice', 25), ('Charlie', 30)]
As you can see, the list is sorted by age from smallest to largest.
Python3 Examples