❮ Previous Next ❯

Python Anonymous / Lambda Function


Lambda functions in Python

In Python, the function which is defined without a name is known as anonymous function.
Here normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.

Lambda functions are used along with built-in functions like filter(), map() etc.

The general form(Syntax) is:

    lambda arguments: expression

Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.

Example;
# lambda function

result = lambda y: y * 5

print(result(10))

Output:

50

Here lambda y: y * 2 is the lambda function. Here y is the argument and y * 2 is the expression that is evaluated and returned.

This function has no name. It returns a function object which is assigned to the identifier result.

result = lambda y: y * 5

is nearly the same as

def result(y):

   return y * 5

filter() function

In Python, filter() function takes a list as arguments inside a function.

The filter() function is called with all the items in the list and lambda function will be passed inside the filter().

Example;

# Program to filter out only the odd items from a list

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

y = list(filter(lambda p: (p%2 != 0) , x))

print(y)

Output:

[1, 3, 5, 7, 9]

map() function

In Python, map() function takes in a function and a list.

The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.

Example;

# Program to tripple each item in a list using map()

numbers = [1,2,3,4]

new_numbers = list(map(lambda y: y * 3 , numbers))

print(new_numbers)

Output:

   [3, 6, 9, 12]

❮ Previous Next ❯


Follow Us




  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved