Member-only story

9 Different ways to use Python Lambda Functions

Python Coding
3 min readSep 14, 2024

--

1. Simple Arithmetic Operations:

add = lambda x, y: x + y
subtract = lambda x, y: x - y
multiply = lambda x, y: x * y
divide = lambda x, y: x / y

print(add(3, 5))
print(subtract(8, 3))
print(multiply(4, 6))
print(divide(10, 2))
8
5
24
5.0

2. Sorting a List of Tuples :

pairs = [(1, 5), (2, 3), (4, 1), (3, 8)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)
[(4, 1), (2, 3), (1, 5), (3, 8)]

3. Filtering a List:

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

4. Mapping a Function to a List:

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet