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

#Programming   #Python  
1_wCDhmP_Tl-mFUSMeN-KTfg.jpeg

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.

countries = ['Bhutan', 'Nicaragua', 'Ghana', 'Andorra']
countries.sort()
print(countries) # ['Andorra', 'Bhutan', 'Ghana', 'Nicaragua']

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).

countries = ['Bhutan', 'Nicaragua', 'Ghana', 'Andorra']
countries_new = []
length = [len(f) for f in countries] # [5, 9, 6, 7]
length_new = length.copy() # DO NOT length_sorted = length
length_new.sort() # [5, 6, 7, 9]
print(length_new)
for i in range(len(length_new)):
    index = length.index(length_new[i])
    countries_new.append(countries[index])
print(countries_new) # ['Ghana', 'Bhutan', 'Andorra', 'Nicaragua']

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.

countries = ['Bhutan', 'Nicaragua', 'Ghana', 'Andorra']
countries.sort(key=len) # len is a built-in function to get length
print(countries) # ['Ghana', 'Bhutan', 'Andorra', 'Nicaragua']

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.

def sortFunc(element):
    return element.index('a') # 'a' is case-sensitive
countries = ['Bhutan', 'Nicaragua', 'Ghana', 'Andorra']
countries.sort(key=sortFunc)
print(countries) # ['Ghana', 'Nicaragua', 'Bhutan', 'Andorra']

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.

countries = ['Bhutan', 'Nicaragua', 'Ghana', 'Andorra']
countries.sort(key=lambda element:element.index('a'))
print(countries) # ['Ghana', 'Nicaragua', 'Bhutan', 'Andorra']

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:

countries = ['Bhutan', 'Nicaragua', 'Ghana', 'Andorra']
countries_iterator = filter(lambda x: len(x) % 2 == 0, countries)
countries_new = list(countries_iterator)
print(countries_new) # ['Bhutan']

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!

Start blogging about your favorite technologies and get more readers

Join other developers and claim your FAUN account now!

17

Authority

103

Total Hits

Discussed tools
Python