Python From Beginner to Advanced

0% completed

Previous
Next
Python - lambda Functions

A lambda function in Python is a small, anonymous function that can have any number of arguments but only one expression. Unlike regular functions defined with def, lambda functions are often used for short, simple operations. They are commonly used in cases where a function is needed temporarily.

Syntax

lambda arguments: expression
  • The lambda keyword is used to define the function.
  • It can take multiple arguments but must contain only one expression.
  • The result of the expression is automatically returned.

Examples

Example 1: Basic Lambda Function

Python3
Python3

. . . .

Explanation

  1. A lambda function named add takes two arguments (x and y).
  2. It returns their sum (x + y).
  3. Calling add(5, 3) outputs 8.

Example 2: Using Lambda with "sorted()" Function

Python3
Python3

. . . .

Explanation:

  1. The list students contains tuples with names and ages.
  2. The sorted() function sorts them based on age (x[1]).
  3. Students are sorted in ascending order by age.

Lambda functions are anonymous, single-expression functions used for simple operations. They are often used with built-in functions like map(), filter(), and sorted(). While they make code concise, they should be used only when a short function is required, as regular functions (def) are easier to read for complex logic.

.....

.....

.....

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