📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Python Lambda Functions

Understanding and using lambda functions in Python, with examples and outputs.

  1. Basic lambda function syntax
  2. Using lambda functions with built-in functions like map(), filter(), and reduce()
  3. Sorting with lambda functions
  4. Conditional expressions in lambda functions
  5. Using lambda functions as arguments
  6. Immediately invoked lambda functions
  7. Limitations and best practices for lambda functions

1. Basic Lambda Function Syntax

# Basic lambda function
square = lambda x: x ** 2
print(f"Square of 5: {square(5)}")
# Output: Square of 5: 25

# Multiple arguments
add = lambda x, y: x + y
print(f"3 + 4 = {add(3, 4)}")
# Output: 3 + 4 = 7

# No arguments
greet = lambda: "Hello, World!"
print(greet())
# Output: Hello, World!

2. Lambda Functions with Built-in Functions

# Lambda with map()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(f"Squared numbers: {squared}")
# Output: Squared numbers: [1, 4, 9, 16, 25]

# Lambda with filter()
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even numbers: {even_numbers}")
# Output: Even numbers: [2, 4]

# Lambda with reduce()
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print(f"Product of numbers: {product}")
# Output: Product of numbers: 120

3. Sorting with Lambda Functions

# Sorting a list of tuples
students = [('Alice', 22), ('Bob', 19), ('Charlie', 24)]
sorted_by_age = sorted(students, key=lambda x: x[1])
print(f"Sorted by age: {sorted_by_age}")
# Output: Sorted by age: [('Bob', 19), ('Alice', 22), ('Charlie', 24)]

# Sorting a list of dictionaries
books = [
    {'title': 'Python Basics', 'price': 30},
    {'title': 'Java Programming', 'price': 45},
    {'title': 'Data Science', 'price': 35}
]
sorted_by_price = sorted(books, key=lambda x: x['price'])
print(f"Sorted by price: {sorted_by_price}")
# Output: Sorted by price: [{'title': 'Python Basics', 'price': 30}, {'title': 'Data Science', 'price': 35}, {'title': 'Java Programming', 'price': 45}]

4. Conditional Expressions in Lambda Functions

# Ternary operator in lambda
is_even = lambda x: 'Even' if x % 2 == 0 else 'Odd'
print(f"Is 4 even? {is_even(4)}")
print(f"Is 7 even? {is_even(7)}")
# Output:
# Is 4 even? Even
# Is 7 even? Odd

# Multiple conditions
grade = lambda score: 'A' if score >= 90 else 'B' if score >= 80 else 'C' if score >= 70 else 'D' if score >= 60 else 'F'
print(f"Grade for 85: {grade(85)}")
print(f"Grade for 65: {grade(65)}")
# Output:
# Grade for 85: B
# Grade for 65: D

5. Lambda Functions as Arguments

def apply_operation(x, y, operation):
    return operation(x, y)

add = lambda x, y: x + y
multiply = lambda x, y: x * y

print(f"10 + 5 = {apply_operation(10, 5, add)}")
print(f"10 * 5 = {apply_operation(10, 5, multiply)}")
# Output:
# 10 + 5 = 15
# 10 * 5 = 50

6. Immediately Invoked Lambda Functions

# Immediately invoked lambda function
result = (lambda x: x ** 2)(5)
print(f"Square of 5: {result}")
# Output: Square of 5: 25

# With multiple arguments
greeting = (lambda name, age: f"Hello, {name}! You are {age} years old.")("Alice", 30)
print(greeting)
# Output: Hello, Alice! You are 30 years old.

7. Limitations and Best Practices

# Lambdas are limited to a single expression
# This is valid:
square = lambda x: x ** 2

# This would be invalid (commented out to avoid syntax error):
# invalid_lambda = lambda x: 
#     if x > 0:
#         return x ** 2
#     else:
#         return 0

# For complex operations, use regular functions instead:
def complex_operation(x):
    if x > 0:
        return x ** 2
    else:
        return 0

print(f"Complex operation on 5: {complex_operation(5)}")
print(f"Complex operation on -5: {complex_operation(-5)}")
# Output:
# Complex operation on 5: 25
# Complex operation on -5: 0