Foundations of Python

You are currently auditing this course.
134 / 134

Lambda Function and List Comprehension




Not able to play video? Try with youtube

A lambda function is a small anonymous function and it is defined by the keyword "lambda".

A lambda function can take any number of arguments, but can only have one expression.

A lambda function is defined and used in the same statement.

Syntax:

lambda arguments : expression

Examples:

Increment a number by 1.

x = lambda a : a + 10
print(x(5))

Multiply two arguments return the result:

x = lambda a, b : a * b
print(x(3, 4))

The concept of lambda can be leveraged further by using this inside a normal function. In the below example, a generic function is created which acts a doubler, tripler or quadrupler or any multiplier.

def multiplier(n):
  return lambda a : a * n

doubler = multiplier(2)
print(doubler(11))

tripler= multiplier(3)
print(tripler(11))

# or can do this directly
print(multiplier(4)(11))

You can also do operations like filter, map, etc using lambda which can also be using normal functions.

In the example below, we will filter the numbers divisible by 3 using different methods.

Method 1: Using a normal function

foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]

def filter_divisbile_by_n(n, numlist):
    return [num for num in numlist if num%n==0]

divisible_by_3 = filter_divisbile_by_n(3, foo)

print("Method 1 output is:")
print(divisible_by_3, "\n")

Method 2: Using a function as an argument

def is_divisbile_by_n(n, num):
    return num%n==0

def filter_divisbile_by_n(is_divisbile_by_n, n, numlist):
    return [num for num in numlist if is_divisbile_by_n(n, num)]

divisible_by_3 = filter_divisbile_by_n(is_divisbile_by_n, 3, foo)

print("Method 2 output is:")
print(divisible_by_3, "\n")

Method 3: Using a lambda as an argument

def filter_divisbile_by_n(div_func, numlist):
    return [num for num in numlist if div_func(num)]

divisible_by_3 = filter_divisbile_by_n(lambda x: x%3 == 0, foo)

print("Method 3 output is:")
print(divisible_by_3, "\n")

Method 4: Using a filter and normal function

def is_divisbile_by_3(num):
    return num%3==0
divisible_by_3 = filter(is_divisbile_by_3, foo)
print("Method 4 output is:")
print(list(divisible_by_3),"\n")

Method 5: Using a filter and lambda function

divisible_by_3 = filter(lambda x: x%3 == 0, foo)
print("Method 5 output is:")
print(list(divisible_by_3),"\n")

Method 6: Using a lambda inside a function

def is_divisbile_by_n(n):
    return lambda num: num%n == 0
divisible_by_3 = filter(is_divisbile_by_n(3), foo)
print("Method 6 output is:")
print(list(divisible_by_3),"\n")

Using lambda with map In the below example, we double the value of each element.

doubled_list = map(lambda x: x*2, foo) print(list(doubled_list))

Using lambda with reduce In the below example, we sum up all elements. from functools import reduce summed_list = reduce(lambda x, y: x + y, foo) print(summed_list)


Please login to comment

6 Comments

How does reduce function work?

  Upvote    Share

Hi Parul,

In Python, the reduce function is a part of the functools module and is used for performing cumulative operations on a sequence of elements. It takes a function and applies it cumulatively to the items of an iterable, reducing the sequence to a single value.

The reduce function performs the following steps:

It takes the first two elements from the iterable and applies the function to them, producing a result (let's call it result).

It takes the next element from the iterable and applies the function to result and the new element, producing a new result.

This process continues until all elements of the iterable are exhausted, and the final result is obtained.

 1  Upvote    Share

Hi, I am not very clear with all the 6 methods shown in the above tutorial of lamba. Can this be explained further in class?

I would also like to know which are situations when a lamba function is used instead of normal function.

  Upvote    Share

 Hi Shila,

Yes you can raise your question in the further class. For now, I'll try to explain you.

A lambda function, also known as an anonymous function, is a way of creating small, one-line functions without having to define them using the `def` keyword. Lambda functions are commonly used when we need to pass a simple function as an argument to another function or when we need to create a function quickly for a short period of time.

The basic syntax of a lambda function is as follows:

lambda arguments: expression

Here, `arguments` is a comma-separated list of input arguments, and `expression` is a single Python expression that is executed when the lambda function is called. The result of this expression is then returned as the result of the lambda function.

For example, let's say we want to create a simple function that squares a given number. We can define this function using the `def` keyword as follows:

def square(x):
    return x ** 2


We can also define the same function using a lambda function as follows:

square = lambda x: x ** 2

Here, the lambda function takes a single argument `x` and returns `x ** 2`.

 1  Upvote    Share

Lambda functions are particularly useful in situations where we need to pass a small function as an argument to another function. For example, the `filter()` function in Python can be used to filter elements from a list based on a given condition. The syntax of the `filter()` function is as follows:

filter(function, iterable)

Here, `function` is a function that takes a single argument and returns either `True` or `False`, and `iterable` is an iterable (such as a list or a tuple) that we want to filter. The `filter()` function returns a new iterable that contains only the elements from the original iterable for which the `function` returns `True`.

We can use a lambda function to define the filtering condition for the `filter()` function. For example, let's say we have a list of numbers and we want to filter out all the even numbers. We can do this using a lambda function as follows:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = list(filter(lambda x: x % 2 == 0, numbers))

Here, the lambda function takes a single argument `x` and returns `True` if `x` is even (i.e., `x % 2 == 0`) and `False` otherwise. The `filter()` function then uses this lambda function to filter out all the even numbers from the `numbers` list.

Another common use case for lambda functions is with the `map()` function in Python, which applies a given function to each element of an iterable and returns a new iterable with the results. The syntax of the `map()` function is as follows:

map(function, iterable)

Here, `function` is a function that takes a single argument and returns a value, and `iterable` is an iterable that we want to apply the function to. The `map()` function returns a new iterable that contains the results of applying the `function` to each element of the original iterable.

Again, we can use a lambda function to define the function to be applied to each element of the iterable. For example, let's say we have a list of numbers and we want to square each of them. We can do this using a lambda function as follows:

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))

Here, the lambda function takes a single argument x and returns x ** 2, which is the squared value of x. The map() function then applies this lambda function to each element of the numbers list and returns a new iterable containing the squared values.

  Upvote    Share

Lambda functions can also be used with other built-in functions in Python, such as sorted(). For example, let's say we have a list of tuples containing names and ages, and we want to sort the list by age. We can do this using a lambda function as follows:

people = [('Alice', 25), ('Bob', 20), ('Charlie', 30), ('Dave', 28)]
sorted_people = sorted(people, key=lambda x: x[1])

Here, the lambda function takes a single argument x, which is a tuple containing a name and an age, and returns the second element of the tuple (i.e., the age). The sorted() function then uses this lambda function as the key argument to sort the people list by age.

In general, lambda functions are used in situations where a small, one-line function is needed for a short period of time, such as when passing a function as an argument to another function or when defining a quick function for data manipulation. However, for more complex functions or functions that will be used frequently, it is generally better to use the def keyword to define a named function instead.

For now, it may still seem a little blurry. You will get a more clear vision of the lambda function when you will practice. Also, run all the codes which i mentioned above to understand the working of lambda function.

  Upvote    Share