Friday 8 March 2024

Lambda Functions in Python

 


Example 1: Basic Syntax

# Regular function

def add(x, y):

    return x + y

# Equivalent lambda function

lambda_add = lambda x, y: x + y

# Using both functions

result_regular = add(3, 5)

result_lambda = lambda_add(3, 5)

print("Result (Regular Function):", result_regular)

print("Result (Lambda Function):", result_lambda)

#clcoding.com

Result (Regular Function): 8

Result (Lambda Function): 8

Example 2: Sorting with Lambda

# List of tuples

students = [("Alice", 25), ("Bob", 30), ("Charlie", 22)]

# Sort by age using a lambda function

sorted_students = sorted(students, key=lambda student: student[1])

print("Sorted Students by Age:", sorted_students)

#clcoding.com

Sorted Students by Age: [('Charlie', 22), ('Alice', 25), ('Bob', 30)]

Example 3: Filtering with Lambda

# List of numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Filter even numbers using a lambda function

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print("Even Numbers:", even_numbers)

#clcoding.com

Even Numbers: [2, 4, 6, 8]

Example 4: Mapping with Lambda

# List of numbers

numbers = [1, 2, 3, 4, 5]

# Square each number using a lambda function

squared_numbers = list(map(lambda x: x**2, numbers))

print("Squared Numbers:", squared_numbers)

#clcoding.com

Squared Numbers: [1, 4, 9, 16, 25]

Example 5: Using Lambda with max function

# List of numbers

numbers = [10, 5, 8, 20, 15]

# Find the maximum number using a lambda function

max_number = max(numbers, key=lambda x: -x)  # Use negation for finding the minimum

print("Maximum Number:", max_number)

#clcoding.com

Maximum Number: 5

Example 6: Using Lambda with sorted and Multiple Criteria

# List of dictionaries representing people with names and ages

people = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 22}]

# Sort by age and then by name using a lambda function

sorted_people = sorted(people, key=lambda person: (person["age"], person["name"]))

print("Sorted People:", sorted_people)

#clcoding.com

Sorted People: [{'name': 'Charlie', 'age': 22}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

Example 7: Using Lambda with reduce from functools

from functools import reduce

# List of numbers

numbers = [1, 2, 3, 4, 5]

# Calculate the product of all numbers using a lambda function and reduce

product = reduce(lambda x, y: x * y, numbers)

print("Product of Numbers:", product)

#clcoding.com

Product of Numbers: 120

Example 8: Using Lambda with Conditional Expressions

# List of numbers

numbers = [10, 5, 8, 20, 15]

# Use a lambda function with a conditional expression to filter and square even numbers

filtered_and_squared = list(map(lambda x: x**2 if x % 2 == 0 else x, numbers))

print("Filtered and Squared Numbers:", filtered_and_squared)

#clcoding.com

Filtered and Squared Numbers: [100, 5, 64, 400, 15]

Example 9: Using Lambda with key in max and min to Find Extremes

# List of tuples representing products with names and prices

products = [("Laptop", 1200), ("Phone", 800), ("Tablet", 500), ("Smartwatch", 200)]

# Find the most and least expensive products using lambda functions

most_expensive = max(products, key=lambda item: item[1])

least_expensive = min(products, key=lambda item: item[1])

print("Most Expensive Product:", most_expensive)

print("Least Expensive Product:", least_expensive)

#clcoding.com

Most Expensive Product: ('Laptop', 1200)

Least Expensive Product: ('Smartwatch', 200)

0 Comments:

Post a Comment

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (118) C (77) C# (12) C++ (82) Course (62) Coursera (180) Cybersecurity (22) data management (11) Data Science (95) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (753) Python Coding Challenge (230) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses