Python Lambda Function

Table Of Content:

  • What Is A Lambda Function?
  • Lambda Function Syntax.
  • Examples Of Lambda Function.
  • Lambda Function With map( ) Function.
  • Lambda Function With filter( ) Function.

(1) What Is A Lambda Function ?

  • Lambda functions are user-defined functions in Python, which have only a single statement to execute.
  • The Lambda function can have any number of arguments but only one expression, which is evaluated and returned.
  • As we know ‘def’ keyword is used to define a normal function, here, the ‘lambda’ keyword is used to define the Lambda function.
  • Lambda functions are the nameless function, which means they can be declared without a name.

(2) Lambda Function Syntax.

lambda arguments: expression
  • arguments: This function can have any number of arguments.
  • expression: but only one expression, which is evaluated and returned.
  • Where ever a function object is required as an argument, you can use the Lambda function.

(3) Examples Of Lambda Function.

Example-1: Printing A Number

func = lambda a : print('Number Is:',a)

print(func)

print(func(5))
Output:
<function <lambda> at 0x000001F70A9CC700>
Number Is: 5

Note:

  • Here we have created a Lambda function that will print a number.
  • As Lambda functions are the nameless function, you need to assign them to some variable to store the function object.
  • You can use the function object to call the Lambda function.

Example-2: Square Of A Number

func = lambda n : n * n

func(4)
Output:
16

Example-3: Adding Numbers

func = lambda a,b,c: print(a+b+c)

func(3,4,5)
Output:
12

(4) Using Lambda Function With map() Function.

  • As we already know a map( ) function takes a function object as an argument, you can pass a lambda function to it.

Example

numbers = [1,2,3,4,5,6]

cube = lambda n: n * n * n

mapping = map(cube,numbers)

number_cubes = list(mapping)

number_cubes
Output:
[1, 8, 27, 64, 125, 216]

Note:

  • Here I am passing the ‘cube’ lambda function to the map( ) function..

(5) Using Lambda Function With filter() Function.

  • As we already know a map( ) function takes a function object as an argument, you can pass a lambda function to it.

Example

numbers = [1,2,3,4,5,6,7,8,9,10]

even = lambda n: n % 2 == 0

filtering = filter(even,numbers)

even_num = list(filtering)

even_num
Output:
[2, 4, 6, 8, 10]

Note:

  • Here I am passing the ‘cube’ lambda function to the map( ) function.

Leave a Reply

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