Primer to Python Lambda Function


Modified:   August 15, 2024
Published:   August 18, 2016

Tags:

Lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created.

The general syntax of a lambda function is quite simple:

lambda argument_list: expression

Sample

1
2
3
>>> f = lambda x, y : x + y
>>> f(1,1)
2

Lambda functions are mainly used in combination with the functions filter(), map() and reduce()

  • map: Apply function to all elements in sequence
  • filter: Apply function to all elements in sequence and return only those elements for which the function returns True
  • reduce: Apply function to all elements in sequence cumulatively

Map

The function map(f,l) applies the function f() to all the elements of the sequence l. It returns a new list with the elements changed by f().

Without lambda:

1
2
3
4
5
6
7
8
def to_fahrenheit(T):
    return ((float(9)/5)*T + 32)
def to_celsius(T):
    return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)

F = map(to_fahrenheit, temp)
C = map(to_fahrenheit, F)

With lambda

1
2
3
4
5
temp = (36.5, 37, 37.5,39)
to_farenheit = lambda x: (float(9)/5)*x + 32    
to_celsius = lambda x: (float(5)/9)*(x-32)
F = map(to_farenheit, temp)
C = map(to_celsius, F)

Filter

The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False.

Here the function will list the odd Fibonacci numbers

1
2
3
4
5
6
7
8
>>> fib = [0,1,1,2,3,5,8,13,21,34,55]
>> odd_lambda = lambda x: x % 2 != 0
>>> result = filter(odd_lambda, fib)
>>> print result
[1, 1, 3, 5, 13, 21, 55]
>>> result = filter(lambda x: x % 2 == 0, fib)
>>> print result
[0, 2, 8, 34]

Reduce

The function reduce(f,l) continually applies the function f() to the sequence l. It returns a single value.

  1. At first the first two elements of sequence are applied to f, i.e. f(s1,s2)
  2. Next f() is applied on the previous result and the third element of the list, i.e. f(f(s1,s2),s3)
  3. The process continues till the last element of the sequence.
1
2
3
4
5
6
>>> from functools import reduce
>>> reduce(lambda x,y: x+y, [47,11,42,14])
114
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102

Reference:



Let me know if you have any questions or comments.
It will help me to improve/learn.


< Older   Further Reading   Newer >