Python From Beginner to Advanced

0% completed

Previous
Next
Python - Lambda Functions

Lambda functions, also known as anonymous functions, are a way to create small, one-off functions in Python. They are defined using the lambda keyword, which is why they are often referred to as "lambda functions".

Lambda functions provide a concise way to perform simple tasks. Unlike regular function definitions (def), which allow for multiple expressions and statements, lambda functions are limited to a single expression. This expression is evaluated and returned when the function is called.

Key Points

  • Syntax Simplicity: Lambda functions reduce the amount of code you write.
  • In-line Usage: Often used in-line with higher-order functions like map(), filter(), and sorted().
  • Limited Functionality: They cannot contain multiple expressions or include commands like loops and multiple conditional branches.

Defining a Lambda Function

A lambda function in Python is defined using the following syntax:

Image
Python3
Python3
. . . .

Explanation:

  • lambda is a keyword to define an anonymous function.
  • The function can take any number of comma-separated parameters.
  • Expression is a single-line code expression.

Example

Creating a simple lambda function to add two numbers.

Python3
Python3

. . . .

Explanation:

  • add = lambda x, y: x + y defines a lambda function with two parameters, x and y, and the expression adds these two numbers.
  • The function is then used to add 5 and 3, storing the result in result.
  • The output is The sum is: 8, demonstrating that the lambda function works as expected.

Using Lambda Functions with Built-in Functions

Lambda functions are commonly used with functions like filter(), map(), and sorted() which expect a function object as one of their arguments.

Example

Using a lambda function with the sorted() function to sort a list of tuples by the second element.

Python3
Python3

. . . .

Explanation:

  • list_of_tuples is defined with three tuples, each containing a number and its string equivalent.
  • sorted() is used to sort the list. The key parameter is a lambda function that takes x (a tuple) and returns the second element of the tuple (x[1]). This tells sorted() to arrange the tuples based on the alphabetical order of the second element in each tuple.
  • The result is Sorted list: [(1, 'one'), (2, 'two'), (3, 'three')], showing the list sorted by the second element of the tuples.

Lambda functions enhance Python's ability to handle functional programming tasks. They allow for quick, on-the-fly function definitions that are often more readable and concise for simple tasks.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next