Functions Using Lambda

journey into python

Helpful links

What is a Python lambda function?

Lambda functions are often used to create small, anonymous functions. They can be used wherever function objects are required that only contain a single line. Lambda functions are fast and easy to create. Like any other function, a Lambda function may have several arguments with the same expression. They are a great way to get started with functional programming in Python.

Example Python lambda function

Lets start with a simple standard function

def add(x,y):
  return x + y
add(2,3)
5

Now lets convert the add function to a lambda

(lambda x,y: x+y)(2,3)
5

The above example demonstrate how to create and use a lambda function.

What is Python lambda used for?

Truthfully, the only time I use Lambda functions is when I want to run a small function against a Pandas dataframe. I am typically dealing with very large dataframes (1 million plus) and I get a nice performance boost doing so.

For the most part it is considered bad form to use lambda’s when they aren’t really needed.

Even the PEP8 style guide strongly discourages their use. See example below.

# The following are equivalent but not recommended

def sub1(x, y):
  return x - y

sub2 = lambda x, y: x - y

# Instead, write your standard function like this

def sub3(x,y): return x-y

test = f'''
PEP8 Recommended Function Usage: {sub1(3,2)}
PEP8 Discouraged Use of Lambda:  {sub2(3,2)}
PEP8 Recommended Function One-Liner: {sub3(3,2)}
'''

print(test)
PEP8 Recommended Function Usage: 1
PEP8 Discouraged Use of Lambda:  1
PEP8 Recommended Function One-Liner: 1

You might be asking two questions:

First: Why did I learn this?

Others may use it and you will need to be able to read their code. Also, as I mentioned earlier, when used correctly it can imporove performance.

Second: Hey, how do you use lambda in Pandas.

That is a great question, but Pandas is a huge topic that would need its own series.

For now, check out how to use lambda on Pandas dataframes here

Pandas in 10 minutes here

What is the difference between AWS Lambda and Python Lambda

Python lambda functions and AWS Lambda are very different and should not be confused with each other. The simplest way to put this is:

  • AWS Lambda is branding for serverless computing
  • Python lambda is a way to simplify a function

To make things even more confusing, you can use Python to write an AWS Lambda, technically writing Python lambda functions inside AWS Lambda. Chew on that one for a while.

Leave a Comment