Writing Anonymous function in Python

Subscribe to my newsletter and never miss my upcoming articles

In this article, I will be writing about the anonymous functions also called the lambda function, their syntax and how to use them with examples.

What are Anonymous function in Python

Anonymous function are functions that is defined without a name. They allow single line functions to be written that might be used once or given a name to be used multiple times.

How to use Anonymous function in Python.

Anonymous function is defined as:

name = lambda argument (s) : expression

They can have many parameters but they can only have one argument. The expression is the one evaluated and then the result returned.

Example of Anonymous function

To write a function to multiply two numbers 2 and 3.

Using the expression:

name = lambda argument(s) : expression

Steps:

Define a name

Assign arguments to the lambda function

Input the expression

Print out the result

To solve the example we have;

mult = lambda x,y:x*y

print(mult(2,3))

Output:

IMG_20200722_220257_802.jpg

In the example above,

mult is the name (identifier).

x,y are arguments.

x*y is the expression to be evaluated for result to be returned.

Anonymous function allows a function to be called immediately.

Usage with built-in function

Anonymous function can be used with built-in function like filter() and map().

Using Anonymous function with Filter()

In using filter(), it takes in a list and a function as an argument. It provides an effective way to filter out all the elements in a list. When the function is called, it returns a new list which contains all the items for which the function evaluates to True.

Example: Using filter() to find, remove and print out all the even numbers in a list.

my_numbers =[1,4,6,2,8,20,22,3,5,7,9,80]
even_numbers = list(filter(lambda x:(x%2==0),my_numbers)

print(even_numbers)

Output:

IMG_20200722_214436_083.jpg

Using the Anonymous function with map()

In using the map(), it accepts a function and a list as it's argument. When it is called, it returns a new list which contains all the items for which the function evaluates but for each item.

Example: Using an Anonymous function to find the square of a number.

numbers = [1, 4,6,8,9,5,12,18]
square = list(map(lambda x: x**2, numbers))

print(square)

Output:

IMG_20200722_213758_358.jpg

Finally, anonymous function can either be used independently as seen in the examples above or inside other functions.

I hope you enjoyed reading this, kindly leave a comment or like this article.

Thank you

Comments (2)

Ruth Ikegah's photo

Nice, Just got to know about this!