Python for Network Engineers

Lambda Expressions in Python

by: George El., March 2019, Reading time: 3 minutes

In this post I will explain lambda expressions in python. Simply put, lambda expressions is another way to create a function in python. However this function has some restrictions. It does not have a name (that’s why they are also called anonymous), they can not have assignments they do not have a ‘return’ keyword and they can only be one line. They usually used when a function is needed to be passed as an argument to another function. So they are used with higher order functions like map, filter, reduce. The syntax is:

lambda [parameters] : expression


lambda x : x
returns x
lambda x : x**2
returns x**2
lambda x,y : x+y
returns x+y
lambda: True
returns True

Lets see an example first with a normal function and then with a lambda function. We will use the map function that accepts as arguments a function and an iterable and executes the function for each of the iterables. It returns a map object and we will use the list() to convert the output to list. In python 2 it is not needed, because it returns a list.

l = [1,2,3,4]
def sq(x):
    return x**2
the above code prints
[1, 4, 9, 16]

Now with lambda
l = [1,2,3,4]
print(list(map(lambda x:x**2,l)))
[1, 4, 9, 16]

Lets see an example with reduce. Lets assume we want to find the product of all elements in a list.

 reduce(lambda x,y: x*y,[1,2,3,4])

Another common example is to use lambda expression with sorted function. The sorted fucntion accepts as key a function that can customize the sort order

['A', 'D', 'a', 'b', 'c', 'z']

as we can see above, because the list contains upper and lower case characters, the sorted function does not provide the output we want. Lets remedy this, by providing as key a lambda function that converts all characters at uppercase. Now the sorted function will have no problem sorting them.

sorted(l, key=lambda x: x.upper())
['a', 'A', 'b', 'c', 'D', 'z']

Last example, lets assume I have a list of names and I want to sort them on the last name. By default it will use the first character to sort them

l =["George Smith","Adam Fry","John Black"]
['Adam Fry', 'George Smith', 'John Black']

Lets see how we can fix it

l =["George Smith","Adam Fry","John Black"]
sorted(l, key=lambda x: x.split()[1])
['John Black', 'Adam Fry', 'George Smith']

What I did is split the full name in a list and use the second (1) element of the list for sorting. If I wanted to sort on the first name I would do this

sorted(l, key=lambda x: x.split()[0])
['Adam Fry', 'George Smith', 'John Black']

In addition in another post I have shown how to sort IP addresses. I will repeat the code here

ip_list = ["","","","",""]

sorted(ip_list, key = lambda ip: [int(ip) for ip in ip.split(".")] )

['', '', '', '', '']

You can find the whole script on the post how to sort ip addresses with python

comments powered by Disqus