Understand Lambda Function with a Simple Example in Python

What is a lambda function?

A lambda function is often called an anonymous function, which you will understand in a moment. The difference between a simple function and a lambda function is small.

Let’s try with an example to explain it.

def multiply_two(x):
    return 2*x
my_lambda = lambda x: 2*x

Which both will return 20. The first one, multiply_two, is a simple function that has a return statement. The lambda function does the same, just defined differently.

Looking at the lambda function.

my_lambda = lambda x: 2*x

You see the structure that you use the key-word lambda and what it takes of input x and what it returns 2*x. In this case we assigned the lambda function to a variable my_lambda. This is not necessary as the use-case below will show.

Why use lambda functions?

It can be convenient to use lambda functions in cases where you want to make simple operations.

Again, a simple example will demonstrate it.

def apply_to_list(the_list, f):
    return [f(x) for x in the_list]

the_list = [6, 3, 9, 1, 4, 2, 8]
print(apply_to_list(the_list, lambda x: x + 5))
print(apply_to_list(the_list, lambda x: x*2))

Which will return.

[11, 8, 14, 6, 9, 7, 13]
[12, 6, 18, 2, 8, 4, 16]

That is nice. You can easily define small functions to make simple functionality you might only need once.

When you understand the syntax of lambda functions it is easy.

Alternatively, you could use the following code the get the same result without using the lambda function.

print([x + 5 for x in the_list])
print([x*2 for x in the_list])

The simplicity of these examples are only meant to teach that lambda functions gives you some flexibility in your programs.

Learn Python


  • 70 pages to get you started on your journey to master Python.
  • How to install your setup with Anaconda.
  • Written description and introduction to all concepts.
  • Jupyter Notebooks prepared for 17 projects.

Python 101: A CRASH COURSE

  1. How to get started with this 8 hours Python 101: A CRASH COURSE.
  2. Best practices for learning Python.
  3. How to download the material to follow along and create projects.
  4. A chapter for each lesson with a descriptioncode snippets for easy reference, and links to a lesson video.

Expert Data Science Blueprint

Expert Data Science Blueprint

  • Master the Data Science Workflow for actionable data insights.
  • How to download the material to follow along and create projects.
  • A chapter to each lesson with a Description, Learning Objective, and link to the lesson video.

Machine Learning

Machine Learning – The Simple Path to Mastery

  • How to get started with Machine Learning.
  • How to download the material to follow along and make the projects.
  • One chapter for each lesson with a Description, Learning Objectives, and link to the lesson video.

Leave a Comment