# What they are and how to use Lambda expressions in Python

They may seem confusing, but they are simple and super useful!

Since I’ve been learning Python, the functions have challenged the laws that govern my thinking. In a way I must confess that I found them too complicated and tried to avoid them. I certainly wasn’t aware of their true usefulness.
It was last Saturday (when I was immersed in a lab about Lambdas in Iron Hack) when something clicked in my head and I started to understand the potential of these expressions. That condensed syntax that allows us to write simple functions in just one line, seemed to me to be something magical.

# Definition of Lambda

In Python, a lambda function refers to a small anonymous function. We call them “anonymous functions” because technically they have no name.
Unlike a normal function, we do not define it with the standard keyword def that we use in Python. Instead, Lambda functions are defined as a line that executes a single expression. These types of functions can take any number of arguments, but can only have one expression.

# Basic syntax

All Lambda functions in Python have exactly the same syntax:

`#I write p1 and p2 as parameters 1 and 2 of the function.lambda p1, p2: expression`

As I can best explain it is by showing you a basic example, let’s see a normal function and an example of Lambda:

`#Here we have a function created to add up.def sum(x,y):    return(x + y)#Here we have a lambda function that also adds up.lambda x,y : x + y#In order to use it we need to save it in a variable.sum_two = lambda x,y : x + y`

As with the list comprehensions, what we’ve done is write the code in one line and clean up the unnecessary syntax.

Instead of using `def` to define our function, we have used the keyword `lambda`; then we write x, y as function arguments, and x + y as expression. In addition, the keyword `return` is omitted, further condensing the syntax.

Finally, and although the definition is anonymous, we store it in the variable `sum_two` to be able to call it from any part of the code, otherwise we could only use it in the line where we define it.

# Lambdas Apply

I want to give you some ideas of where the Lambdas could be applied. Below I have created some examples applying Lambdas for different purposes. So you can better understand how they work.

# Lambda in Pandas DataFrame with the apply() method

I think we can apply a Lambda function to data cleaning in Pandas with the apply() method, something that I think can be useful to avoid creating a loop that goes through the whole DataFrame:

`#import pandas and numpy to create a DataFrameimport pandas as pdimport numpy as np#created a DataFrame with two columns, Celsius and Kelvin, both with equal datadata = {'Celsius': [22, 36, 20, 26, 30, 38],        'Kelvin': [22, 36, 20, 26, 30, 38]}#created the DataFrame with its index and Celsius and Kelvin columnsdf = pd.DataFrame(data, index = ['Londres','Madrid','Barcelona','Sevilla','Cádiz','Lima'])#Creating a lambda function to pass the degrees Celsius to Kelvinto_kelvin = lambda x: (x + 273,15)#apply the Lambda to the [Kelvin] column with the apply() methoddf = df['Kelvin'].apply(to_kelvin)#In the column 'Kelvin' the Lambda has been applied, the 273.15 applied by Lambda has been added to x (in this case 22 from London)London (295, 15)Madrid (309, 15)Barcelona (293, 15)Seville (299, 15)Cadiz (303, 15)Lima (311, 15)Name: Kelvin, dtype: object`

## Output :

London (295, 15)
Barcelona (293, 15)
Seville (299, 15)
Lima (311, 15)

# Lambda in lists with the filter() method

The filter() function is able to return a new collection with the filtered elements that meet a condition.
We can check, for example, what the even numbers are in a given list. To do this we will pass a list to a Lambda in the following way:

`#I have a list with many numberscheck = [38,24,99,42,2,3,11,23,53,21,3,53,77,12,34,92,122,1008,26]#I create a variable and apply filter() and lambdafilt = filter(lambda x: x % 2 == 0, check)#I create a variable to convert the result of 'filt' into a list pairs = list(filt)#Finally I get the list with the results that have returned True when passing the filterprint(pairs)`

## Output :

[38, 24, 42, 2, 12, 34, 92, 122, 1008, 26]

# Conclusions

I hope that you find this article interesting, that it helps you and that you understand the examples and, above all, that you can put everything you have learned into practice in your day-to-day life.

It has helped me a lot to be able to transmit my knowledge to you ;)

If you liked my article about “What are Lambda expressions and how to use them in Python” and you want to know more about my future articles, you can follow me in Medium and in Twitter @borjauria

Written by

Written by

## Borja Uría

#### Data Analyst 🚀 working at roams.es . Luckily, we have #Python 🐍#DataAnalytics ♥ | #Pandas | #webscraping | #PowerBI | Learning from everyone & 🤖 , every day! 