Lambda Functions in Python

20 creative examples of Lambda Functions for Expressive Coding

A lambda function in Python is like a mini-function that you can create quickly and use without naming it.

It’s also called an “anonymous” or “inline” function because you don’t give it a proper name like you do with regular functions using the def keyword.

When to use it?

  • Lambda functions are handy when you need a small function for a short task, like sorting a list or performing simple operations on elements.
  • Use them in situations where you don’t want to define a full function with a name.

When not to use it?

  • Avoid using lambda functions for complex tasks or if you need to reuse the same function multiple times.
  • Lambda functions are best suited for simple, one-time-use cases.

Why it is called custom function?

  • Lambda functions are sometimes referred to as “custom functions” because you can define them for a specific purpose and customize them on the spot. They are like custom-made tools for specific tasks.

Let’s look at the following examples of Lambda Functions:

Example 1: Basic Lambda

add = lambda x, y: x + y
result = add(3, 4)
print(result) # Output: 7

Example 2: Sorting a List of Tuples

students = [("Alice", 25), ("Bob", 30), ("Charlie", 20)]
students.sort(key=lambda student: student[1])
print(students) # Output: [('Charlie', 20), ('Alice', 25), ('Bob', 30)]

Example 3: Filtering Even Numbers

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

Example 4: Using Lambda with Map

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

Example 5: Combining Lists with Lambda

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
student_info = list(map(lambda x, y: (x, y), names, scores))
print(student_info) # Output: [('Alice', 85), ('Bob', 92), ('Charlie', 78)]

Example 6: Lambda in List Comprehension

numbers = [1, 2, 3, 4, 5]
doubled = [(lambda x: x * 2)(num) for num in numbers]
print(doubled) # Output: [2, 4, 6, 8, 10]

Example 7: Lambda with Conditional Logic

is_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(is_even(4)) # Output: Even

Example 8: Sorting a List of Dictionaries

students = [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}]
students.sort(key=lambda student: student['score'])
print(students) # Output: [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}]

Example 9: Using Lambda with Recursion

factorial = lambda n: 1 if n == 0 else n * factorial(n-1)
print(factorial(5)) # Output: 120

Example 10: Sorting a List of Strings by Length

words = ['apple', 'banana', 'cherry', 'date', 'fig']
words.sort(key=lambda word: len(word))
print(words)
# Output: ['date', 'fig', 'apple', 'banana', 'cherry']

Example 11: Extracting Initials from Names

names = ['Alice Johnson', 'Bob Smith', 'Charlie Brown']
initials = list(map(lambda name: ''.join(word[0] for word in name.split()), names))
print(initials) # Output: ['AJ', 'BS', 'CB']

Example 12: Generating Fibonacci Sequence

from functools import reduce
fibonacci = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]], range(n - 2), [0, 1])
print(fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Example 13: Simulating a Dice Roll

import random
roll_dice = lambda: random.randint(1, 6)
print("You rolled a", roll_dice()) # Output: A random number between 1 and 6

Example 14: Creating a Mini Calculator

calculator = lambda x, y, op: (x + y) if op == 'add' else (x - y) if op == 'subtract' else (x * y) if op == 'multiply' else (x / y) if op == 'divide' else None
result = calculator(5, 3, 'multiply')
print("Result:", result) # Output: 15

Example 15: Reversing a List Using Lambda

reverse_list = lambda lst: lst[::-1]
original_list = [1, 2, 3, 4, 5]
reversed_list = reverse_list(original_list)
print(reversed_list) # Output: [5, 4, 3, 2, 1]

Example 16: Checking Palindromes

is_palindrome = lambda s: s == s[::-1]
print(is_palindrome("racecar")) # Output: True

Example 17: Converting Fahrenheit to Celsius

fahrenheit_to_celsius = lambda f: (f - 32) * 5/9
print(fahrenheit_to_celsius(98.6))
# Output: 37.0 (approximately)

Example 18: Counting Vowels in a String

count_vowels = lambda s: sum(1 for char in s if char.lower() in 'aeiou')
print(count_vowels("Hello, World!"))
# Output: 3

Example 19: Simulating a Timer

import time

start_timer = lambda: time.time()
end_timer = lambda start_time: time.time() - start_time

start = start_timer()
time.sleep(2)

print("Elapsed time:", end_timer(start))
# Output: Elapsed time: 2.0 (approximately)

Example 20: Generating a Password with Random Characters

import string
import random

generate_password = lambda length: ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
password = generate_password(8)

print("Generated Password:", password)
# Output: A random 8-character password

--

--

Responses (1)