Jima Victor
webcodespace

webcodespace

Anonymous Function in Python

Anonymous Function in Python

Jima Victor's photo
Jima Victor
·Jul 30, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • So what is a lambda function?
  • When to use the anonymous function in python:

Objective: In this brief post, you're going to learn what anonymous functions are, and when to use them

Anonymous functions in python?

If you are looking to know what an anonymous function in python is? Then it's more likely that you have experience working with anonymous functions in javascript.

While they are called anonymous functions in javascript, they are referred to as lambda functions in python.

So what is a lambda function?

Lambda functions are functions in python without names. These functions are small and they can collect multiple arguments but can only have one expression.

Syntax:

function = lambda parameter : expression

From the above syntax, you can see that the lambda function is created using the lambda keyword and afterward, the parameters of the function can be written, then whatever expression you want for your function can be written after the colon.

Example:

function = lambda firstNumber, secondNumber : firstNumber + secondNumber
print(function(1, 2))

Result:

3

When to use the anonymous function in python:

Since lambda functions can only have one expression, it makes sense to use them when you want to carry out a really small task. Lambda functions are also best used in other functions like map(), reduce() and filter() where they can be passed as arguments.

Example with the filter() function:

numbers = [1,3,3,4,5,6,4,3,6,7]
morethanfive =  list(filter(lambda x : x > 5, numbers)) 
print(morethanfive)

Result:

[6, 6, 7]
 
Share this