HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

6) Advanced Python Concepts Lesson

Python Lambda Functions

10 min to complete · By Martin Breuss

Lambda expressions, also called anonymous functions, allow you to define small functions in a single line of code. They can make your code more concise, but they can be a difficult concept to grasp, so there is a trade-off in keeping your code human-friendly and readable.

Lambdas and Normal Functions

In this lesson, you'll take a look at a lambda expression to learn how it relates to a normal function:

def square_root(x):
    return x**2

In the code snippet above, you defined a function, square_root(), that takes an integer, x, as its argument and returns that number squared.

You can write the same logic in a one-liner lambda expression:

squared = lambda x: x**2

In both cases, you've defined a function object, square_root and squared respectively, that you can call with a number as an argument to get the same results:

print(square_root(4) == squared(4))  # OUTPUT: True

As you can see, lambda expressions are just another way to write a function in Python.

Colorful illustration of a light bulb

Info: If you're planning to assign a name to your function object, then you should always opt to define the function using the def keyword. While it's possible to give a name to a lambda expression, this is not how they're intended to be used. They are called "anonymous functions" for a reason!

So, if it's just another way to write a function, why bother with lambda expressions at all?

Anonymous Functions

As mentioned in the note above, you shouldn't use a lambda expression to name a function object. Lambdas are meant to be anonymous functions that you use as a one-off input to another function.

You've probably used Python's sorted() function before. This function has an optional key parameter that allows you to pass a function to apply some logic to each element before performing the sort. For example, if you wanted to sort the ingredients list of tuples shown below by their amounts, you can do this by passing an anonymous function to the key parameter:

ingredients = [("carrots", 2), ("potatoes", 4), ("peppers", 1)]
sorted(ingredients, key=lambda x: x[1])

The sorted() function will apply the lambda expression to each item of the iterable, in this case, each tuple of the shape ("name", number). Similar to a loop variable, you can think that x will be each of the tuples contained in the list. You define that with the first part of the lambda expression, lambda x:.

Then, you're defining what the anonymous function should do with each of the tuples, x, and in this case, you're telling the code to pick out the second item of each tuple with x[1].

This means that your lambda expression will pick the second item of each tuple, which is the numerical amounts, use them to create a new iterable, and sort your original values based on the sorted order of that new iterable:

# OUTPUT:
# [('peppers', 1), ('carrots', 2), ('potatoes', 4)]

As you can see, this code outputs a new list that is sorted ascending by the second element in the tuples, which would be hard to achieve without using the lambda expression.

Functional Programming

This way of programming is part of a paradigm called functional programming that is different from object-oriented programming, which you'll mostly work on within this course. Python has the capability to work in both ways, which is one of the reasons why it's such a versatile language.

At the same time, this fact also explains why lambda expressions can sometimes appear foreign. You're used to working with Python in an object-oriented pattern, and from that perspective, lambda functions don't quite fit the mold.

A lamb on a green pasture - Photo by https://unsplash.com/@rayner Rayner Simpson on Unsplash

Photo by Rayner Simpson https://unsplash.com/@rayner

While you won't need to use lambda expressions in your programs, it's still useful to understand the basics about them and when it might be helpful to use one.

Other examples of functions that can take function objects as arguments are Python's filter(), map(), and reduce() functions. They are often used with lambda expressions to define the logic that'll be applied to all elements in an iterable. These functions are also a common way to start thinking about concepts that are common in functional programming:

squares = list(map(lambda x: x**2, range(10)))
print(squares)  
# OUTPUT: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Using map() with a lambda expression as its first input and an iterable range() object as the second input, you just calculated all square numbers from 0 to 10 and added them to a new list. Pretty neat and compact!

Colorful illustration of a light bulb

Note: You need to explicitly convert the output of map() to a list, because filter(), map() and reduce() return generator objects instead of lists in Python 3.

If you're thinking that you could have done the same thing more concisely with a list comprehension, then you're right in thinking so! The list comprehension can do the same thing and is arguably more readable for many developers:

squares = [x**2 for x in range(10)]
print(squares)  
# OUTPUT: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

As you can see, there's often no real advantage to using a lambda expression in these situations. They are most useful when you need to pass a function as an argument to another function, as mentioned further up. For example, you couldn't pass a list comprehension to the key parameter in sorted() because the function expects another function object.

Colorful illustration of a light bulb

Additional Resources

Summary: What is the Python Lambda Function

  • Lambda expressions are anonymous functions that are primarily used to pass function logic to another function as an argument.
  • The receiving function can use this logic and, for example, apply it to all elements in an iterable.
  • Lambda expressions are more common in functional programming and might seem unfamiliar. Most of the time, you can use different logic instead of a lambda expression, for example, by defining a function object or using a list comprehension instead.