Lambda Functions In Python

Lerekoqholosha
2 min readOct 4, 2021

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

Unlike standard python functions which are defined using the ‘ def keyword’, a ‘function name’, a ‘ function body’, and a ‘ return statement’.

Tutorial 1: Squaring the input value

A normal function for squaring the input would look like this:

def square(x) return x**2

lambda function:

L=lambda x:x**2

Let’s look at output of the above functions:

print(square(2) print(L(2))) 4 4

We can also try to write this lambda function as follows:

(lambda x:x * 2)(2) 4

Tutorial 2: Doubling the input value

P = lambda x: x*2 p(3) 6

Tutorial 3: Raising input

p = lambda x, y: x**y p(2,5) 32

The next step is to look at how we can use lambda function together with mapping, List Comprehension, if else condition, and filtering.

Tutorial 4: List Comprehension

list_comp = [lambda x=x: x*10 for x in range(1, 13)] for num in list_comp: print(num()) 10 20 30 40 50 60 70 80 90 100 110 1200

Tutorial 5: Mapping

lst = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(map(lambda x: x*2, lst)) print(final_list) [10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

Tutorial 6: Filtering

sequences = [10,2,8,7,5,4,3,11,0, 1] filtered_result = filter(lambda x: x > 4, sequences) print(list(filtered_result)) [10, 8, 7, 5, 11]

Tutorial 7: Lambda Function with If Else Condition

x = lambda n: n**2 if n%2 == 0 else n**3 print(x(4)) print(x(3)) 16 27

Conclusion

Lambda functions are great, they allow us to write simple functions with minimal code.

We can use lambda functions when an anonymous function is required for a short period of time.

Thank you for reading:).

Please let me know if you have any feedback.

Originally published at https://www.linkedin.com.

--

--

Lerekoqholosha

I am a data scientist with 1 year of experience working with Python.