Skip to main content

Lambda Functions

Lambda functions in Python, also known as anonymous functions, are small, unnamed functions defined using the lambda keyword. These functions can have any number of arguments but only one expression. They are syntactically restricted to a single line and are used primarily for creating small, throwaway functions.

Syntax of Lambda Functions

The syntax for a lambda function is:

lambda arguments: expression

  • lambda: This keyword is used to create a new lambda function.
  • arguments: A comma-separated list of arguments that the function accepts.
  • expression: An expression that the function evaluates and returns. The expression must be a single line.

Defining and Using Lambda Functions

Basic Example

Here’s a simple example of a lambda function that adds two numbers:

add = lambda x, y: x + y result = add(2, 3) print(result) # Output: 5


Using Lambda Functions Inline

Lambda functions are often used in places where a function is required temporarily, often in higher-order functions like map(), filter(), and sorted().

Example with map()

The map() function applies a given function to each item in an iterable (like a list) and returns a map object (an iterator).

numbers = [1, 2, 3, 4, 5] squared = map(lambda x: x ** 2, numbers) print(list(squared)) # Output: [1, 4, 9, 16, 25]



Example with filter()

The filter() function constructs an iterator from elements of an iterable for which a function returns true.

numbers = [1, 2, 3, 4, 5] even_numbers = filter(lambda x: x % 2 == 0, numbers) print(list(even_numbers)) # Output: [2, 4]


Example with sorted()

The sorted() function returns a new sorted list from the elements of any iterable.

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] # Sorting by the second element of the tuple sorted_pairs = sorted(pairs, key=lambda pair: pair[1]) print(sorted_pairs) # Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


Using Lambda Functions with reduce()

The reduce() function from the functools module repeatedly applies a function to the elements of an iterable, reducing it to a single value.

from functools import reduce numbers = [1, 2, 3, 4, 5] sum_numbers = reduce(lambda x, y: x + y, numbers) print(sum_numbers) # Output: 15


Example: Sorting with Lambda Functions

Lambda functions can be particularly useful for custom sorting.

students = [ {'name': 'John', 'age': 25, 'grade': 88}, {'name': 'Jane', 'age': 22, 'grade': 92}, {'name': 'Dave', 'age': 23, 'grade': 85}, ] # Sort by age sorted_by_age = sorted(students, key=lambda student: student['age']) print(sorted_by_age) # Output: [{'name': 'Jane', 'age': 22, 'grade': 92}, {'name': 'Dave', 'age': 23, 'grade': 85}, {'name': 'John', 'age': 25, 'grade': 88}]


# Sort by grade sorted_by_grade = sorted(students, key=lambda student: student['grade']) print(sorted_by_grade) # Output: [{'name': 'Dave', 'age': 23, 'grade': 85}, {'name': 'John', 'age': 25, 'grade': 88}, {'name': 'Jane', 'age': 22, 'grade': 92}]


Lambda functions in Python provide a concise way to create small, unnamed functions at runtime. They are particularly useful in scenarios where you need a simple function for a short period, such as in functional programming constructs like map(), filter(), and reduce(). While powerful, it's often best to use them for simple operations to keep the code readable and maintainable. For more complex functions, defining a standard function with def is recommended.




Comments

Popular posts from this blog

TechUplift: Elevating Your Expertise in Every Click

  Unlock the potential of data with SQL Fundamental: Master querying, managing, and manipulating databases effortlessly. Empower your database mastery with PL/SQL: Unleash the full potential of Oracle databases through advanced programming and optimization. Unlock the Potential of Programming for Innovation and Efficiency.  Transform raw data into actionable insights effortlessly. Empower Your Data Strategy with Power Dataware: Unleash the Potential of Data for Strategic Insights and Decision Making.

Relationships between tables

In Power BI, relationships between tables are essential for creating accurate and insightful reports. These relationships define how data from different tables interact with each other when performing analyses or creating visualizations. Here's a detailed overview of how relationships between tables work in Power BI: Types of Relationships: One-to-one (1:1):   This is the most common type of relationship in Power BI. It signifies that one record in a table can have multiple related records in another table. For example, each customer can have multiple orders. Many-to-One (N:1):   This relationship type is essentially the reverse of a one-to-many relationship. Many records in one table can correspond to one record in another table. For instance, multiple orders belong to one customer. One-to-Many (1:N):   Power BI doesn't support direct one-to-many relationships.  One record in table can correspond to many records in another table.  Many-to-Many (N:N):  ...

SQL Fundamentals

SQL, or Structured Query Language, is the go-to language for managing relational databases. It allows users to interact with databases to retrieve, manipulate, and control data efficiently. SQL provides a standardized way to define database structures, perform data operations, and ensure data integrity. From querying data to managing access and transactions, SQL is a fundamental tool for anyone working with databases. 1. Basics of SQL Introduction : SQL (Structured Query Language) is used for managing and manipulating relational databases. SQL Syntax : Basic structure of SQL statements (e.g., SELECT, INSERT, UPDATE, DELETE). Data Types : Different types of data that can be stored (e.g., INTEGER, VARCHAR, DATE). 2. SQL Commands DDL (Data Definition Language) : CREATE TABLE : Define new tables. ALTER TABLE : Modify existing tables. DROP TABLE : Delete tables. DML (Data Manipulation Language) : INSERT : Add new records. UPDATE : Modify existing records. DELETE : Remove records. DQL (Da...