Lambda Functions In Python

In this article, we will examine when we should use lambda functions, when we shouldn’t use them, and what they are in general.

Lambda Function Syntax

Lambda functions differ from normal functions, they do not have a function name and are written on only 1 line.

lambda arguments(x): expression

Simply put, the arguments are entered after the lambda keyword, and the action is written after the “:”.

lambda num: num ** num

Using Lambda With Scalar Value

Using a lambda with a single value is easier and faster than a regular function. Below you can find the syntax.

(lambda x: x + 1) (24)

As a result, it will return you the value 25. The lambda function uses the value in the parentheses as the parameter.

Using Iterator Tools With Lambda

Using iterator tools with Lambda is very easy and increases performance, speed significantly if you don’t know what iterator tools are you can read this article.

l1 = [10 , 20 , 30 , 3 , 1 , 4]
f1 = filter(lambda x: x > 6 , l1)

# Output: [10 , 20 , 30]

It is not only limited to filter but also works well with the map function. You can find the syntax below.

l1 = [10 , 20 , 30 , 23]
f1 = map(lambda x: x * 6 , l1)

# Output: [60, 120, 180, 138]

Using Lambda Function With DataFrame

You can use lambda to operate on DataFrames, it will give you great convenience in your data science projects.

For example, the apply function is one of the most compatible with lambda. Let’s write a code about it.

import pandas as pd

# assign data of lists.  
data = {"Name": ['Tom', 'Dan', 'Mark'],
        "Age": [20, 21, 19]}  
# Create DataFrame  
df = pd.DataFrame(data)  

df.apply(lambda x: x["Age"] + 1 , axis = 1)

Consider a large data set, about 50 million people have age and name information (yes, country data) they will all be 1 year older after 1 year. This code increases all ages by +1.

Discouraged Use Cases

Normal functions are more useful than Lambda in certain situations. In this section, we will examine the disadvantages of Lambda functions.

1 – Lambda Naming

If your function needs a name, definitely use regular functions. Lambda functions are created not to be stored.

It should also be noted that def functions are more attractive and easier to find than Lambda functions in naming. Lambda naming often appears as a variable, making it hard to find.

# Bad Usage
funcName = lambda x: x + 2

# Good Usage
def funcName():
  x + 2

# Perfect Usage
def funcName(): x + 2
2 – Don’t Use Functions in Lambda Functions

Do you remember that we used the Map function with Lambda, if you are going to use a function inside a lambda, don’t use a lambda, instead add the function directly to the map.

This concept applies to everything else, it’s better not to use functions in Lambda.

# Bad Usage
map(lambda x: sum(x), list)

# Good Usage
map(sum, list)

# Also Good Usage
map(lambda y: math.fmod(y , 2), list)

Also good use! I used the fmod function even though I just said you shouldn’t use a function in a Lambda function.

The reason this isn’t bad is that ideally, you can use functions with 2 or more arguments in Lambda.

3 – Drop Lambda If It Doesn’t Fit in 1 Line

Lambda functions that are too long to read won’t do you any good, make sure you don’t ruin your code to save space.

We’re not living in the 1990s, your RAM won’t explode for two or three lines. It’s important to write indented codes when needed.

# Awful Usage
filter(lambda x: x > 25 and x < 100 or x > 250)

# Good Usage
def func(x):
  if x > 25 and x < 100:
    return True

  if x > 250:
    return True

    return False

Codes longer than this will further reduce readability. If you are using too many conditional cases, use the def function.

Thanks For Reading & Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *