Lambda Functions in Python
Lambda functions are small anonymous functions used for short,
one-line operations. They are commonly used with functions like
map(), filter(), and sorted().
What is a Lambda Function?
A lambda function is a function without a name, written in a single line. It can take any number of arguments but only one expression.
# normal function
def square(x):
return x * x
# lambda function
square = lambda x: x * x
print(square(5))
✔ Short and concise
✔ Used for simple logic
✔ Improves readability when used correctly
Lambda with Multiple Arguments
Lambda functions can take more than one argument.
add = lambda a, b: a + b
print(add(3, 7))
Lambda with map()
map() applies a function to every item in an iterable.
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
print(squares)
Lambda with filter()
filter() selects elements that satisfy a condition.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
📝 Practice:
Use a lambda function to filter numbers greater than 10 from the list
Use a lambda function to filter numbers greater than 10 from the list
[5, 12, 18, 7, 20].