When solving some complex or simple algorithm or may be working on some data sets, the need to sort your items may arise.
Python has a built-in function called sorted()
that sorts the elements of a given iterable in a specific order then returns a list.
In this article, we will also look at the Lambda
function and how it helps.
Consider the code block below:
age = { "John" : 12, "Charles" : 14, "Chris" : 20, "Esther" : 10}
x = age.items()
sorted_age = sorted(x, key = lambda y : y[1])
print(sorted_age)
# returns a list of tuples sorted from the youngest:
#[('Esther', 10), ('John', 12), ('Charles', 14), ('Chris', 20)]
Let's look at each line:
age
: A dictionary of individuals with their age as values.x
: A variable used to hold the returned value fromage.items()
.items()
is used to transformage
into a list of iterable tuples.
print(x)
# returns dict_items([('John', 12), ('Charles', 14), ('Chris', 20), ('Esther', 10)])
sorted_age
: holds a list of tuples returned fromsorted(x, key = lambda y : y[1])
you can read more about thelambda
function but let me do a brief explanation.
The lambda function is the same as your regular function. Let's just call it a shortcut to the regular python function (
def func(): return something
) but with more restriction and concise syntax. See pseudocode below:
(lambda x : x + 1) (4) = lambda 4 : 4 + 1
= 5
When the sorted()
function is executed, the key
variable is called for each element of x
. since y[1]
is returned from the lambda
function, we are telling sorted()
to only sort the second element in each tuple of dict_items([('John', 12), ('Charles', 14), ('Chris', 20), ('Esther', 10)])
.
Hence the result is a list of individuals sorted by their age.