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
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
andy
) 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:
- Open your Python environment (IDE or terminal).
- Copy and paste the code into a Python script or directly into the terminal.
- Run the script or execute the code block.
- You will see the output printed in the console: 25 for the sum of squares and the sorted list.