Lesson 2: Lambda Functions

In this lesson, we will explore Lambda Functions in Python. Lambda functions are a key feature in Python that allows for the creation of small, anonymous functions on the fly. They are used in situations where a simple function is required for a short period and don’t need a formal function definition using the def keyword.

We will cover the following topics in detail:

  • Anonymous Functions
  • Lambda Syntax
  • Use Cases of Lambda Functions

1. Anonymous Functions

An anonymous function is a function that is defined without a name. Normally, in Python, when we define a function, we use the def keyword followed by a function name. However, sometimes we don’t need a function to have a name because we only want to use it in a specific place (e.g., inside a map, filter, or sorted function). This is where lambda functions come into play.

An anonymous function is created using the lambda keyword, hence it is also referred to as a lambda function.

Advantages of Anonymous Functions:
  • Concise and easy to write: Lambda functions allow you to define a function in a single line of code, which is particularly useful when you need a small function for a short period.
  • No need to assign a function name: This makes it useful in situations where a function is required temporarily, such as passing a function as an argument to higher-order functions.
Example: Traditional Function vs Lambda Function

Using a normal function definition:

python
def add(x, y):

return x + y

 

result = add(3, 4)

print(result)

 

Output:

Output
7

 

Using a lambda function:

python
add = lambda x, y: x + y

 

result = add(3, 4)

print(result)

 

Output:

Output
7

 

Both examples do the same thing, but the lambda function is more compact and is defined without the use of a name.

2. Lambda Syntax

The syntax for a lambda function is quite simple and follows this general structure:

python
lambda arguments: expression

 

  • lambda: This is the keyword that tells Python you are defining a lambda function.
  • arguments: These are the inputs to the function, similar to parameters in a regular function. A lambda function can take any number of arguments (including none).
  • expression: This is the logic or the operation that the lambda function performs. It must be a single expression, and the result of this expression will be returned automatically.
Example: Basic Lambda Function
python
multiply = lambda a, b: a * b

 

result = multiply(5, 6)

print(result)

 

Output:

Output
30

 

Explanation:

  • The lambda function multiplytakes two arguments, a and b, and returns their product.
  • We pass the arguments 5and 6 to the function, which results in 30.
Lambda Function with One Argument

Lambda functions can also have a single argument:

python
square = lambda x: x * x

 

result = square(5)

print(result)

 

Output:

Output
25

 

Explanation:

  • Here, the lambda function takes one argument xand returns the square of x.
  • We call the function with the value 5, which returns 25.
Lambda Function with No Arguments

You can also define a lambda function with no arguments:

python

greet = lambda: “Hello, World!”

 

message = greet()

print(message)

 

Output:

Output
Hello, World!

 

Explanation:

  • This lambda function does not take any arguments and simply returns the string “Hello, World!”.

3. Use Cases of Lambda Functions

Lambda functions are particularly useful in scenarios where you need a small function for a short period. Below are some common use cases for lambda functions:

a. Lambda with map()

The map() function is used to apply a given function to all items in an input list. Lambda functions are often used with map() when you need to apply a simple operation to a list of values.

Example: Doubling the elements of a list

python

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

doubled = list(map(lambda x: x * 2, numbers))

 

print(doubled)

 

Output:

csharp
[2, 4, 6, 8, 10]

 

Explanation:

  • The lambda function lambda x: x * 2is applied to each element in the list numbers to double it.
  • map()returns an iterator, which we convert into a list using list().
b. Lambda with filter()

The filter() function is used to filter items from an iterable based on a condition. You can use a lambda function to define the condition.

Example: Filtering out even numbers from a list

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

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

 

print(even_numbers)

 

Output:

csharp
[2, 4, 6]

 

Explanation:

  • The lambda function lambda x: x % 2 == 0checks if a number is even.
  • filter()returns an iterator with the elements for which the lambda function returns True, and we convert it into a list.
c. Lambda with sorted()

The sorted() function can be used to sort a list based on a custom sorting criterion. Lambda functions are often used to define the key by which the list should be sorted.

Example: Sorting a list of tuples by the second element

python
data = [(1, ‘apple’), (3, ‘banana’), (2, ‘cherry’)]

sorted_data = sorted(data, key=lambda x: x[1])

 

print(sorted_data)

 

Output:

css
[(1, ‘apple’), (3, ‘banana’), (2, ‘cherry’)]

 

Explanation:

  • The lambda function lambda x: x[1]is used to sort the tuples by their second element (the fruit name).
  • The keyparameter of the sorted() function allows us to specify how the elements should be compared.
d. Lambda with reduce()

The reduce() function from the functools module can be used to accumulate a result by applying a binary function cumulatively to the items in an iterable.

Example: Calculating the product of a list of numbers

python

from functools import reduce

 

numbers = [1, 2, 3, 4]

result = reduce(lambda x, y: x * y, numbers)

 

print(result)

 

Output:

Output
24

 

Explanation:

  • The lambda function lambda x, y: x * ymultiplies the elements of the list.
  • reduce()applies this lambda function cumulatively to the elements of the list to calculate the product.

4. Summary

In this lesson, we covered lambda functions in Python:

  • Anonymous Functions: Lambda functions are unnamed functions, useful for short, temporary operations.
  • Lambda Syntax: The syntax consists of the lambdakeyword, followed by the arguments and a single expression.
  • Use Cases: Lambda functions are often used with higher-order functions like map(), filter(), sorted(), and reduce(), where small, simple functions are needed for a short time.

Lambda functions are a powerful tool in Python that allow you to write cleaner and more concise code, especially when dealing with simple operations. They are widely used in functional programming paradigms and when working with Python’s built-in higher-order functions.


Comments

Leave a Reply

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