Skip to main content
Practice

Simplifying Functions with Lambda Functions

Lambda functions are a special Python syntax for creating functions in a short and simple manner.

Unlike regular functions, lambda functions have no name to identify them and are written in a single line.


Characteristics of Lambda Functions

Lambda functions are one-time use small functions.

Regular functions are defined using the def keyword, but lambda functions are defined using the lambda keyword.

They are particularly useful for handling simple calculations or data manipulations in a concise way.

Lambda functions are defined in the following format.

Basic Structure of Lambda Functions
lambda arg1, arg2, ... : expression

In this format, the arguments are the inputs to the function, and the expression is the calculated result returned using those arguments.

For example, a lambda function that adds two numbers can be defined as follows.

Example of a Lambda Function
# Lambda function to add two numbers
add = lambda a, b: a + b

result = add(3, 5)

# Prints 8
print(result)

Examples of Using Lambda Functions

Lambda functions are mainly used for simple calculations and data manipulation.

In the code above, add refers to a lambda function that adds two numbers, and when add(3, 5) is called, it prints the result, 8.

Lambda functions are often passed as arguments to other functions to perform short operations.

For example, you can specify the sorting criteria by setting the key function to a lambda when sorting a list.

Sorting with Lambda Functions
# A list consisting of 3 tuples
points = [(1, 2), (3, 1), (5, 0)]

# Sort the list in ascending order based on the second element of each tuple
sorted_points = sorted(points, key=lambda x: x[1])

# Prints [(5, 0), (3, 1), (1, 2)]
print(sorted_points)

Here, key=lambda x: x[1] sorts the list based on the second element of each tuple.


While lambda functions are simple and useful, they are not suitable for handling complex logics.

For operations that require multiple lines of code or debugging, it's better to use regular functions.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.