Python Lambda Functions

Learn Python @

Lambda functions, also known as anonymous functions, are a powerful feature in Python that allow you to create small, inline functions without the need for a formal def statement. Lambda functions are concise and versatile, making them a valuable tool in your Python programming arsenal. In this article, we’ll explore Python’s Lambda functions in depth, providing real-world examples and their corresponding outputs for a hands-on learning experience. Lambda functions in Python are a valuable tool for writing concise and expressive code. They are versatile and can be used in various scenarios, such as sorting, filtering, and mapping data.

What are Lambda Functions?

Lambda functions in Python are small, anonymous functions defined using the lambda keyword. They are often used for short, simple operations that can be expressed in a single line of code. The basic syntax of a lambda function is as follows:

lambda arguments: expression

Here, arguments represent the input parameters to the function, and expression is the operation performed on those arguments. Lambda functions can take multiple arguments but must consist of a single expression.

Lambda Functions in Action

Let’s dive into some real-world examples to understand how lambda functions work:

Example 1: Sorting a List of Tuples

students = [('Alice', 95), ('Bob', 80), ('Charlie', 75)]
# Sort the list of tuples by the second element (marks)
sorted_students = sorted(students, key=lambda x: x[1])


[('Charlie', 75), ('Bob', 80), ('Alice', 95)]

In this example, we used a lambda function as the key argument to the sorted() function. The lambda function lambda x: x[1] extracts the second element (marks) from each tuple, enabling us to sort the list of students based on their marks.

Example 2: Filtering Even Numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use a lambda function to filter even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))


[2, 4, 6, 8, 10]

In this example, we utilized a lambda function with the filter() function to extract even numbers from a list.

Example 3: Calculating Square Roots

import math
# Create a list of numbers
numbers = [9, 16, 25, 36, 49]
# Use a lambda function to calculate square roots
square_roots = list(map(lambda x: math.sqrt(x), numbers))


[3.0, 4.0, 5.0, 6.0, 7.0]

Here, we employed a lambda function with the map() function to calculate the square root of each number in a list.

When to Use Lambda Functions

Lambda functions are particularly useful in situations where you need a simple, short function for a specific task. However, they are not a replacement for regular functions defined with def. Use lambda functions when the function logic is brief and can be expressed in a single line.

Author: user