Join us

Python – Lambda, the Tiny Yet Powerful Function Inside a Function


Image from Wikimedia Commons

In the last article, we saw how List Comprehension can help us to filter and/or sort lists (or arrays) to populate new ones. In this issue, we delve into a tiny, yet powerful, feature that helps in lists and more.

Consider a normal sort() function as below.

This piece of code will sort countries[] alphabetically. Now, what if we want to sort the list according to ascending number of characters? We will need to count the length of each element, sort them in ascending order, then store the corresponding element (and not the length).

sort(key=..., reverse=...) by default will sort in ascending order. We can set parameter reverse to True for descending order. If we would like to sort in a custom order, we use parameter key to specify a function for the sorting operation.

key=len will get the length of each element, and then sort ascending by it. We can also define our custom function to be called.

In the above example, key=sortFunc searches each element for the first occurrence of the character 'a', and sorts according to that index. Note that 'a' and 'A' are treated differently as strings are case-sensitive. The above can be simplified into a single line of code via the keyword lambda. lambda signifies that what follows is the code to a small function and not a function name. The above can then be re-written as follows.

It has the format lambda arguments:expression, where arguments is a comma-separated list of arguments that is fed into the expression.

lambda can be used in many places, and not limited to be used with key. Consider the following:

The filter function goes through countries, testing length of element to be of even number. filter outputs to an object, we, therefore, need to convert it into a list to be printed.

What other examples can you think of? The possibilities are infinite!

Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

User Popularity



Total Hits



Mentioned tools