Python

Introduction

Lambda functions in Python provide a concise and functional approach to writing small, unnamed functions. These functions are often used when a short-term function is needed, and they are syntactically simpler than traditional functions defined with the ‘def’ keyword.

Lambda functions are particularly useful when working with functions that take another function as input, such as map(), filter(), and sorted(). In this tutorial, we will explore what lambda functions are, how to define them, and some common use cases.

Objective

The objective of this tutorial is to introduce Python’s lambda functions, show how to use them for simple tasks, and understand their structure and functionality. By the end of this guide, you will be able to write and run basic lambda functions in Python.

Code Example

# Example of a lambda function in Python

sum_of_squares = lambda x, y: x**2 + y**2
print(sum_of_squares(3, 4)) # Output: 25

# Sorting a list of tuples based on the second element
data = [(1, 2), (3, 1), (5, 0)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data) # Output: [(5, 0), (3, 1), (1, 2)]

Program Structure & Explanation

The lambda function in Python is defined using the lambda keyword, followed by parameters, a colon, and the expression that will be returned.

For example:

  • lambda x, y: x**2 + y**2 is a lambda function that takes two inputs (x and y) and returns their squares summed.
  • sorted(data, key=lambda x: x[1]) sorts a list of tuples based on the second element of each tuple.

Running the Program

To run the above program, follow these steps:

  1. Open your Python environment (IDE or terminal).
  2. Copy and paste the code into a Python script or directly into the terminal.
  3. Run the script or execute the code block.
  4. You will see the output printed in the console: 25 for the sum of squares and the sorted list.
© 2025 Learn Programming

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)