Member-only story

Lambda functions, also known as anonymous functions, are concise functions in Python defined using the lambda
keyword. They are useful in situations where a small, temporary function is needed for a short period. Here are some examples of lambda functions in different scenarios:
1. Basic Arithmetic Operation:
add = lambda x, y: x + y
result = add(3, 5) # Result: 8
2. Filtering a List:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# Result: [2, 4, 6, 8]
3. Mapping a List:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
# Result: [1, 4, 9, 16, 25]
4. Sorting a List of Tuples by the Second Element:
pairs = [(1, 3), (2, 1), (4, 5), (3, 2)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
# Result: [(2, 1), (3, 2), (1, 3), (4, 5)]
5. Conditional Expression:
is_even = lambda x: True if x % 2 == 0 else False
result = is_even(4) # Result: True
6. Creating a Simple Calculator:
calculator = lambda x, y, operation: x + y if operation == 'add' else x - y
result = calculator(5, 3, 'add') # Result: 8
7. Key Function for Sorting Strings by Length:
words = ['apple', 'banana', 'kiwi', 'orange']
sorted_words = sorted(words, key=lambda x: len(x))
# Result: ['kiwi', 'apple', 'banana', 'orange']
8. Checking for Palindrome:
is_palindrome = lambda s: s == s[::-1]
result = is_palindrome('radar') # Result: True
9. Using map
with Multiple Lists:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list(map(lambda x, y: x + y, list1, list2))
# Result: [5, 7, 9]