Python3 Lambda Function

Python  Lambda Function

 Anonymous/Lambda Function :

   In Python, anonymous function is a function that is defined without a name.
  
  While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
 
  Lambda functions are used extensively along with built-in functions like filter(),map(),reduce() .

Syntax:
 
                 lambda arguments: expression

Example

       double=lambda x: x*2

       print(double(5))

output: 10

       def double(x):
             return x*2

       print(double(5))

output: 10

       #example using filter() function
       lst=[1,2,3,4,5]
       even_lst=list(filter(lambda x: (x%2==0),lst))
       print(even_lst)

output:  [2,4]

       #example using map() function
       lst=[1,2,3,4,5]
       new_lst=list(map(lambda x: (x+2),lst))
       print(new_lst)

output: [3,4,5,6,7]

       #example using reduce() function
       from functools import reduce

       lst=[1,2,3,4,5]
       new_lst=list(reduce(lambda x,y: x*y ,lst))
       print(new_lst)

output: 120





Comments

Popular posts from this blog

Python3

Python3 Function Arguments

Python3 File Handling