5) f. Lambda Expressions

Note: This is an advanced topic. If you have absolutely no prior programming experience you can go ahead and skip this topic. If you skip it you’ll still be fine with your Python learning. This topic just introduces another way of doing something that you already know. Later after you’re done with the whole course and gained an all round knowledge of Python you can always come back an attempt this concept.

In Python list objects have several utility methods that allow manipulation of its elements. One of them is the sort method.

1
2
 Output:
[('Anna', 30), ('Chris', 21), ('Julie', 29), ('Max', 22), ('Max', 25)]



In this example you have a list of tuples that contain a person’s name and his age. If you apply the sort method, the list is sorted by people’s names in the alphabetical order first and then by their ages.

But what if we wanted to sort these people by their ages first? Luckily the sort method has a parameter called key that allows you to specify how elements of the list are compared.

We could do something like this.

1
2
 Output:
[('Chris', 21), ('Max', 22), ('Max', 25), ('Julie', 29), ('Anna', 30)]




For each element the comparator function is applied which swaps the age and the name. Then the age takes priority in the comparison. But there is a more compact way to state the same thing.

1
2
3
4
p = [('Max', 25), ('Anna', 30), ('Chris', 21), ('Max', 22), ('Julie', 29)]
p.sort(key=lambda element: (element[1], element[0]))

print(p)




We can use a lambda expression to describe a simple function in one line of code. Note: You don’t need to provide parenthesis in the lambda expression.

Such lambda expressions are often used when providing similar “functional” arguments to various functions. In other words, when you’re calling a function, you need to provide an argument that is also a function. See the following example.

1
2
Output:
('Anna', 30)



Here we determine the oldest person out of the same list by providing the same lambda expression to the max function.

Passing default values:

If your function contains default values for an argument then just write the lambda expression including those default values.

1
2
3
4
5
Output:
0
0
11
11



Lambda functions make your life easier because they are a quick way to define a simple function. Let’s come back to an example that we had seen in the chapter “Common Usage Methods across all Data Structures”.

Return an iterator from elements of iterable which make function return true.
1
2
3
Output:
['Frank', 'Eric']
['Frank', 'Eric']




This example illustrates how powerful lambda functions can be. You have available a “filter” function that can be applied to filter through any data structure.

To make a decision on what to filter it accepts the name of a function, my_test, that returns either True or False as each element is passed through it.