Python Mastery: 50 lambda Function in Various Scenarios for Data Manipulation

btd
7 min readDec 2, 2023
Photo by Muriel Liu on Unsplash

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:

--

--

btd
btd

No responses yet