Lambda Functions

Learn how lambda functions work in Python by playing around with the examples provided in the lesson.

Lambda functions

Lambda functions sound like they are going to be something complicated, but they are actually very simple.

Let’s continue with the previous example, where we have a list of rectangles defined by a pair of values (width, height). For example, (3, 2) defines a rectangle that is 3 units wide by 2 units high. We wish to sort them by increasing area. To do this, we define the area function, as shown below.

Press + to interact
def area(x):
return x[0]*x[1]
p = [(3, 3), (4, 2), (2, 2), (5, 2), (1, 7)]
q = sorted(p, key=area)
print(q) # [(2, 2), (1, 7), (4, 2), (3, 3), (5, 2)]

In the example above, we needed to create a function, called area. This is a very small function that will probably only be used in one place. There surely has to be a better way.

Well, there is. You can use lambda syntax to create a simple function in a Python expression. Here is how we could replace our ...

Access this course and 1400+ top-rated courses and projects.